user1554736
user1554736

Reputation:

Generate vector from comparison

I like to generate a vector containing 0s and 1s from a comparison of a vector with the elements of a list. I have the following vector:

functions=c("abline", "as.numeric", "attach", "data.frame", "ddply", "mean")

This "functions" vector now should be comared to a list of vectors containing a subset of this vector. The list looks like this:

[[1]]
[1] "data.frame"

[[2]]
[1] "data.frame" "ddply"      "mean"      

[[3]]
[1] "data.frame" "abline"      "attach"      "mean"
... 

As a result I would like to produce a vector following the order and length of the "functions" vector containing a 1 for each element matching the "functions" vector and an 0 for not available. All of those i would like to put into a dataframe. For this three list elements this result would look something like the following:

    "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

Has anybody an idea how I could achieve this?

Best Sab.

Upvotes: 2

Views: 134

Answers (2)

James
James

Reputation: 66834

You can use an nested 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

Or just a single one, if you use factor and 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

Upvotes: 0

Joris Meys
Joris Meys

Reputation: 108523

Create the data

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")
)

Then you could simply do:

> 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

Upvotes: 1

Related Questions