如何从Col2
值中过滤Col3
值。例如,我需要仅针对Col2
真值返回Col2
值。
我的数据框:
Col1 Col2 Col3
Check first,second,first,four,Five true,true,false,true,false
预期数据框:
Col1 Col2
Check first,second,four
请帮我解决这个问题。
dput,
structure(list(Col1 = "Check", Col2 = "first,second,first,four,Five",
col3 = "true,true,false,true,false"), class = "data.frame", row.names = c(NA,
-1L), .Names = c("Col1", "Col2", "col3"))
答案 0 :(得分:0)
创建data.frame" db"
Col1<-c("Check","Check2")
Col2<-c("first,second,first,four,Five","first,second,first,four")
Col3<-c("true,true,false,true,false","false,true,false,true")
db<-as.data.frame(cbind(Col1,Col2,Col3))
Col1 Col2 Col3
1 Check first,second,first,four,Five true,true,false,true,false
2 Check2 first,second,first,four false,true,false,true
按Col3过滤Col2
logical_value<-lapply(strsplit(as.character(db[,3]),","),as.logical)
list_Col2<-strsplit(as.character(db[,2]),",")
out<-NULL
for (i in 1:length(list_Col2))
{
out[[i]]<-(unlist(list_Col2[i]))[unlist(logical_value[i])]
}
输出
out
[[1]]
[1] "first" "second" "four"
[[2]]
[1] "second" "four"
答案 1 :(得分:0)
您提出的问题在R
中非常标准,但数据的显示不是。
您的数据似乎更适合列表,因此我首先将其转换为向量列表:
dlist <- lapply(lapply(df, strsplit, ","), unlist)
print(dlist)
$Col1
[1] "Check"
$Col2
[1] "first" "second" "first" "four" "Five"
$col3
[1] "true" "true" "false" "true" "false"
然后很容易将其恢复到预期的结果:
df2 <- data.frame(Col1 = dlist$Col1,
Col2 = paste0(dlist$Col2[as.logical(dlist$col3)], collapse = ","))
print(df2)
Col1 Col2
1 Check first,second,four