3

Suppose you have a list of character vectors:

set.seed(42)
x <- lapply(sample(10:50), function(x) {
  sapply(1:x, function(y) {
    paste(sapply(y, sample, x=letters, size=sample(5:10, 1)), collapse='')
  })
})

You would like to apply a vectorized operation across this entire list. One option is to unlist(x), and then apply the vectorized function:

y <- nchar(unlist(x))

What is the most efficient way to get y back into the same list structure as x? Is there a better way to approach this problem?

4

2 回答 2

4

An alternative would be to use the as.relistable and relist functions like this:

y <- as.relistable(x)
z <- nchar( unlist(x) )
z <- relist(z,y)
str(head(z))
#List of 6
# $ : int [1:47] 7 8 6 6 6 5 8 10 10 5 ...
# $ : int [1:50] 7 9 9 6 7 10 7 6 10 8 ...
# $ : int [1:21] 8 7 9 5 9 10 5 5 8 9 ...
# $ : int [1:41] 5 9 9 9 5 5 5 5 10 9 ...
# $ : int [1:33] 9 5 9 9 8 9 7 9 6 10 ...
# $ : int [1:28] 5 5 5 9 8 8 8 6 9 6 ...
于 2013-04-30T21:30:16.280 回答
2

I'm having difficulty understanding why lapply is not the answer (and also why Josh deleted his answer that said exactly that 6 hours ago.)

charcounts <- lapply(x, nchar )
str(head(charcounts))
List of 6
 $ : int [1:47] 7 8 6 6 6 5 8 10 10 5 ...
 $ : int [1:50] 7 9 9 6 7 10 7 6 10 8 ...
 $ : int [1:21] 8 7 9 5 9 10 5 5 8 9 ...
 $ : int [1:41] 5 9 9 9 5 5 5 5 10 9 ...
 $ : int [1:33] 9 5 9 9 8 9 7 9 6 10 ...
 $ : int [1:28] 5 5 5 9 8 8 8 6 9 6 ...
于 2013-05-01T04:11:10.080 回答