lapply works over an array or a single element?

2019-02-26 07:17发布

问题:

I'm slightly confused as to whether lapply works on a list or on a vector. See two examples below

  1. 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 
    
  2. 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
    

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?

回答1:

lapply will work on whatever is the highest level which defines the structure of the R object.

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

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