lapply works over an array or a single element?

后端 未结 1 751
孤独总比滥情好
孤独总比滥情好 2021-01-23 06:25

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,

相关标签:
1条回答
  • 2021-01-23 06:40

    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
    
    0 讨论(0)
提交回复
热议问题