R 基于列表中的值列表的数据帧子集
我有一个包含参与者ID和观察结果的数据框。我还有一些需要从此数据框中删除的参与者ID的列表-我想删除与此参与者ID关联的整行。我尝试了以下操作:R 基于列表中的值列表的数据帧子集,r,dataframe,conditional-statements,rows,R,Dataframe,Conditional Statements,Rows,我有一个包含参与者ID和观察结果的数据框。我还有一些需要从此数据框中删除的参与者ID的列表-我想删除与此参与者ID关联的整行。我尝试了以下操作: ListtoRemove <- as.list(ListtoRemove) NewDataFrame <- subset(OldDataFrame,OldDataFrame$ParticipantsIDs!=ListtoRemove) 数据示例: structure(list(ParticipantsIDs = structure
ListtoRemove <- as.list(ListtoRemove)
NewDataFrame <-
subset(OldDataFrame,OldDataFrame$ParticipantsIDs!=ListtoRemove)
数据示例:
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)
结构(列表)参与者SIDS=结构(c(2L、1L、3L、4L、,
标签=c(“B0002”、“B001”、“B003”、“B004”、“L004”,
“M003”,class=“factor”),年龄=结构(c(3L,1L,4L,2L,
5L,6L),标签=c(“15”,“23”,“45”,“53”,“65”,“98”),等级=
“factor”)),class=“data.frame”,row.names=c(NA,
-(6升)
ListtoRemoveNewDataFrame[!NewDataFrame[,1]%在%unlist中(ListtoRemove),]
#参与者年龄
#[1,][B001”“45”
#[2,][B0002”“15”
#[3,]“B003”“53”
#[4,][L004”“98”
我认为您提供的代码中可能有一些错误
您使用子集
的方式表明NewDataFrame
是一个data.frame
,但您给了我们一个矩阵
。我的代码以任何一种方式工作,但您的子集将失败(以与您显示的不同的方式)
as.list(B004,M003)
在以下三点上可能是错误的:
- 如果这些是变量的名称,那么我们就没有它们李>
- 如果这些是字符串,那么我们看到了
as.list(B004、M003)
#组件列表(B004,M003)中出错:未找到对象“B004”
as.list(1,2,3)
仅list
-如果第一个参数被忽略,这里2和3将被忽略(因此我们将只看到“B004”
,而不是M003
;也许您的意思是list(“B004”,“M003”)
或c(“B004”,“M003”)
相反,我使用了
ListtoRemove如果您使用的是数据帧,则更易于阅读的方法是:
# 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))
#创建data.frame
df使用您的数据(ListtoRemove略经编辑-我希望这是正确的):
输出:
> data_subset
ParticipantsIDs Age
[1,] "B001" "45"
[2,] "B0002" "15"
[3,] "B003" "53"
[4,] "L004" "98"
我最终使用了:
data_subset = data[!data[, "ParticipantsIDs"] %in% unlist(ListtoRemove), ]
它工作得很好。是来自NewDataFrame
的dput
是什么B004
和M003
?变量(如编写的)还是字符串(目前是语法错误)?谢谢。是的,对不起,我在制作示例时忘记将其作为数据帧。我无法使用原始数据帧。“没有办法……数据框”…下次请考虑<代码> dPT(头(x))< /> >而不是给我们一个不正确的结构。当你用标签()搜索问题时,读上面的段落,建议使用“<代码> dPUTE())/代码>数据。“谢谢你,无论如何,这个线程确实给了我所需要的答案。”MonikaGrigorova。
data_subset=data[!data[,"ParticipantsIDs"] %in% unlist(ListtoRemove),]
> data_subset
ParticipantsIDs Age
[1,] "B001" "45"
[2,] "B0002" "15"
[3,] "B003" "53"
[4,] "L004" "98"
data_subset = data[!data[, "ParticipantsIDs"] %in% unlist(ListtoRemove), ]