Reputation: 1045
Given list test
, how do I find any numbers that repeat exactly 3 times in test[[2]]
and 4 times in test[[3]]
? In this particular example, I want an output that gives me 3 and 6 in [[2]] and 10 in [[3]].
test <- list(c(1:10),c(1:10,3,3,6,6),c(1:10,10,10,10))
I am able to generate a table for each vector, test2
.
lapply(test,table)
But when I tried to equate the table to 1:3
, which I stored as the names of test
, I get logical(0)
for each vector.
names(test) <- 1:3
lapply(test,function(x) table(x)==names(x))
Any idea what went wrong and what the simplest solution is?
Upvotes: 0
Views: 832
Reputation: 34733
I'm not sure what you were after with your approach, but this will return the numbers appearing twice:
lapply(seq_along(test), function(ii) which(tabulate(test[[ii]]) == ii))
# [[1]]
# integer(0)
#
# [[2]]
# [1] 10
#
# [[3]]
# integer(0)
Upvotes: 0
Reputation: 1668
If you run lapply(test, names)
you would see that the names
function applied to each list element just returns NULL. Under the hood I think lapply is just passing the contents of the sublist and not the sublist itself to the function (just like when you use double square brackets to subset - try comparing names(test[[1]])
to names(test[1])
).
Using your original idea, if what you want is a vector of logicals, you could try this instead:
lapply(1:3, function(x) table(test[x]) == x)
Upvotes: 1
Reputation: 7163
To generate a list of table:
tab <- lapply(test, table)
To get the number of times 10
appear in each object in the list:
lapply(tab, '[', "10")
[[1]]
10
1
[[2]]
10
2
[[3]]
10
3
Upvotes: 0