R:根据列表中的数值列表对数据框进行子集。

问题描述 投票:0回答:1

我有一个包含参与者ID和观察结果的数据框架。我还有一个需要从这个数据框架中删除的一些参与者ID的列表--我想删除与这个参与者ID相关的整行。我已经尝试了以下方法。

ListtoRemove <- as.list(ListtoRemove)
NewDataFrame <-    
subset(OldDataFrame,OldDataFrame$ParticipantsIDs!=ListtoRemove)

这给出了两个警告,但没有删除行。

1: In `!=.default`(DemographicsALL$subject_label, AllSibs) :
longer object length is not a multiple of shorter object length
2: In is.na(e1) | is.na(e2) :
longer object length is not a multiple of shorter object length
> 

数据的例子。

structure(list(ParticipantsIDs = structure(c(2L, 1L, 3L, 4L, 
6L, 5L), .Label = c("B0002", "B001", "B003", "B004", "L004", 
"M003"), class = "factor"), Age = structure(c(3L, 1L, 4L, 2L, 
5L, 6L), .Label = c("15", "23", "45", "53", "65", "98"), class =      
"factor")), class = "data.frame", row.names = c(NA, 
-6L))

ListtoRemove <- as.list(B004,M003)

谢谢!

r dataframe conditional-statements rows
1个回答
1
投票
NewDataFrame[ !NewDataFrame[,1] %in% unlist(ListtoRemove), ]
#      ParticipantsIDs Age 
# [1,] "B001"          "45"
# [2,] "B0002"         "15"
# [3,] "B003"          "53"
# [4,] "L004"          "98"

我认为你提供的代码中可能存在一些错误。

  1. 你使用 subset 隐隐约约 NewDataFrame 是一个 data.frame但你给了我们一个 matrix. 我的代码在两种情况下都能用,但你的 subset 将会失败(与你所展示的方式不同)。
  2. as.list(B004, M003) 也许有三点是错误的。

    • 如果这些是变量的名字,那么我们就没有这些变量。
    • 如果这些是字符串,那么我们看到的是

      as.list(B004, M003)
      # Error in as.list(B004, M003) : object 'B004' not found
      
    • as.list(1, 2, 3) 只是 list-定义了第一个参数,这里忽略了2和3(所以我们只会看到 "B004",不 M003;也许你的意思是 list("B004", "M003")c("B004", "M003")?

相反,我用了

ListtoRemove <- list("B004","M003")

1
投票

如果你使用的是数据框架,一个更容易阅读的方式是。

# create data.frame
df <- data.frame(ParticipantsIDs = c("B001", "B0002", "B003", "B004", "M003", "L004"), 
                        Age = c("45", "15", "53", "23", "65", "98"))

# vector containing ids to remove
ids.remove <- c('B004','M003')

df

# subset df by rows where ParticipantsIDs are not found in ids.remove
subset(df, !(ParticipantsIDs %in% ids.remove))

1
投票

使用你的数据(ListtoRemove稍加编辑--我希望这是正确的)。

data=structure(c("B001", "B0002", "B003", "B004", "M003", "L004", 
"45", "15", "53", "23", "65", "98"), .Dim = c(6L, 2L), .Dimnames = list(
NULL, c("ParticipantsIDs", "Age")))
ListtoRemove <- list("B004","M003")

怎么样:

data_subset=data[!data[,"ParticipantsIDs"] %in% unlist(ListtoRemove),]

输出。

> data_subset
     ParticipantsIDs Age 
[1,] "B001"          "45"
[2,] "B0002"         "15"
[3,] "B003"          "53"
[4,] "L004"          "98"

0
投票

我最后使用data_subset=data[!data[, "ParticipantsIDs"]%in% unlist(ListtoRemove),],效果很好。谢谢大家的帮助!

© www.soinside.com 2019 - 2024. All rights reserved.