我喜欢从矢量与列表元素的比较中生成包含0和1的向量。一世 有以下向量:
functions=c("abline", "as.numeric", "attach", "data.frame", "ddply", "mean")
现在,这个“函数”向量应该被同化为包含该向量子集的向量列表。该列表如下所示:
[[1]]
[1] "data.frame"
[[2]]
[1] "data.frame" "ddply" "mean"
[[3]]
[1] "data.frame" "abline" "attach" "mean"
...
因此,我想按照“函数”向量的顺序和长度生成一个向量,该向量包含与“函数”向量匹配的每个元素的1和不可用的0。所有这些我想把它放到数据帧中。对于这三个列表元素,此结果将类似于以下内容:
"abline" "as.numeric" "attach" "data.frame" "ddply" "mean"
1 0 0 0 1 0 0
2 0 0 0 1 1 1
3 1 0 1 1 0 1
有人知道如何实现这个目标吗?
最佳Sab。
答案 0 :(得分:1)
创建数据
functions=c("abline", "as.numeric", "attach", "data.frame", "ddply", "mean")
mylist <- list(
c("data.frame"),
c("data.frame","ddply","mean"),
c("data.frame","abline","attach","mean")
)
然后你可以这样做:
> solution <- lapply(mylist,function(i) as.numeric(functions %in% i))
> mydf <- as.data.frame(do.call(rbind,solution))
> names(mydf) <- functions
> mydf
abline as.numeric attach data.frame ddply mean
1 0 0 0 1 0 0
2 0 0 0 1 1 1
3 1 0 1 1 0 1
答案 1 :(得分:0)
您可以使用嵌套的sapply
:
list <- list("data.frame",c("data.frame","ddply","mean"),c("data.frame","abline","attach","mean"))
sapply(functions,function(x) sapply(list,function(y) as.numeric(x%in%y)))
abline as.numeric attach data.frame ddply mean
[1,] 0 0 0 1 0 0
[2,] 0 0 0 1 1 1
[3,] 1 0 1 1 0 1
或者只是一个,如果您使用factor
和table
:
do.call("rbind",lapply(list,function(x) table(factor(x,levels=functions))))
abline as.numeric attach data.frame ddply mean
[1,] 0 0 0 1 0 0
[2,] 0 0 0 1 1 1
[3,] 1 0 1 1 0 1