问题描述
我来lapply是否工作清单上或矢量略有困惑。见下面
I'm slightly confused as to whether lapply works on a list or on a vector. See two examples below
-
下面,平均函数施加在数字的阵列,即,1至5个
Here, the mean function is applied over an array of numbers, ie, 1 to 5
x = list(a=1:5, b=rnorm(10))
x
#$a
#[1] 1 2 3 4 5
#
#$b
#[1] -0.57544290 0.51035240 0.43143241 -0.97971957 -0.99845378
#[6] 0.77389008 -0.08464382 0.68420547 1.64793617 -0.39688809
lapply(x,mean)
#$a
#[1] 3
#
#$b
#[1] 0.1012668
但在这里,runif函数施加在该阵列的每个元素
But here, the runif function is applied over each individual element of the array
x = 1:4
lapply(x,runif)
#[[1]]
#[1] 0.5914268
#[[2]]
#[1] 0.6762355 0.3072287
#[[3]]
#[1] 0.8439318 0.8488374 0.1158645
#[[4]]
#[1] 0.8519037 0.8384169 0.2894639 0.4066553
我的问题是,究竟是什么lapply工作呢?数组或一个单独的元素?它是如何正确地选择它取决于功能?
My question is, what exactly does lapply work on? an array or an individual element? And how does it choose it correctly depending on the function?
推荐答案
lapply
将在什么是定义第r对象的结构的最高级别的工作。
lapply
will work on whatever is the highest level which defines the structure of the R object.
如果我有4个独立的整数, lapply
将在每个整数工作:
If I have 4 individual integers, lapply
will work on each integer:
x <- 1:4
lapply(x, identity)
#[[1]]
#[1] 1
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 3
#
#[[4]]
#[1] 4
然而,如果我有一个列表
长度== 2各含2个值, lapply
将在每个工作列表对象。
If however I have a list
of length==2 each containing 2 values, lapply
will work on each list object.
x <- list(1:2,3:4)
lapply(x, identity)
#[[1]]
#[1] 1 2
#
#[[2]]
#[1] 3 4
这篇关于lapply工作在一个数组或一个单一的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!