apply 家族可以进行伪矢量化, 最简单最常用的是 lapply 是 list apply的缩写,参数是某个函数,将此函数作用于列表中的每一个元素上面,并返回另一个列表中
> prime_factors <- list(
+ two = 2,
+ three = 3,
+ four = c(2,2),
+ five = 5,
+ six = c(2,3),
+ seven = 7,
+ eight = c(2,2,2),
+ nine = c(3,3),
+ ten = c(2,5)
+ )
> head(prime_factors)
$two
[1] 2
$three
[1] 3
$four
[1] 2 2
$five
[1] 5
$six
[1] 2 3
$seven
[1] 7
> lapply(prime_factors,unique)
$two
[1] 2
$three
[1] 3
$four
[1] 2
$five
[1] 5
$six
[1] 2 3
$seven
[1] 7
$eight
[1] 2
$nine
[1] 3
$ten
[1] 2 5
还可以使用vapply函数 返回vector 第三个参数是其返回的模板
> vapply(prime_factors,length,numeric(1))
two three four five six seven eight nine ten
1 1 2 1 2 1 3 2 2 还有一个sapply的使用 简化列表 不需要模板 ,简化到一个合适的数组或向量中
> sapply(prime_factors,unique)
$two
[1] 2
$three
[1] 3
$four
[1] 2
$five
[1] 5
$six
[1] 2 3
$seven
[1] 7
$eight
[1] 2
$nine
[1] 3
$ten
[1] 2 5
>
2424

被折叠的 条评论
为什么被折叠?



