我有一个包含参与者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)
答案 0 :(得分:2)
NewDataFrame[ !NewDataFrame[,1] %in% unlist(ListtoRemove), ]
# ParticipantsIDs Age
# [1,] "B001" "45"
# [2,] "B0002" "15"
# [3,] "B003" "53"
# [4,] "L004" "98"
我认为您提供的代码中可能存在一些错误。
subset
的方式表明NewDataFrame
是data.frame
,但是您给了我们matrix
。我的代码无论哪种方式都可以工作,但是您的subset
将会失败(与您显示的方式不同)。 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
;也许您的意思是{ {1}}还是list("B004", "M003")
?相反,我使用了
c("B004", "M003")
答案 1 :(得分: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))
答案 2 :(得分: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"
答案 3 :(得分:0)
我最终使用:
data_subset = data[!data[, "ParticipantsIDs"] %in% unlist(ListtoRemove), ]
效果很好。