2

我喜欢通过将向量与列表元素进行比较来生成包含 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

有谁知道我怎么能做到这一点?

最好的萨布。

4

2 回答 2

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
于 2012-08-09T11:08:29.873 回答
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

或者只是一个,如果你使用factorand 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
于 2012-08-09T11:18:02.240 回答