【问题标题】:R: repeat elements of a list based on another listR:基于另一个列表重复列表的元素
【发布时间】:2012-05-29 17:03:02
【问题描述】:

我已经搜索过这个但徒劳无功。 问题是我有两个列表,首先是要重复的元素 例如

my.list<-list(c('a','b','c','d'), c('g','h'))

第二个列表是每个元素要重复的次数

repeat.list<-list(c(5,7,6,1), c(2,3))

我想创建一个新列表,其中 my.list 中的每个元素都基于 repeat.list 重复 IE。 结果:

[[1]]
[1] "a" "a" "a" "a" "a" "b" "b"  "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d" 
[[2]]
[1] "g" "g" "h" "h" "h" 

提前感谢您的帮助

【问题讨论】:

    标签: r list repeat


    【解决方案1】:

    使用mapply:

    mapply(rep, my.list, repeat.list)
    [[1]]
     [1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d"
    
    [[2]]
    [1] "g" "g" "h" "h" "h"
    

    lapply 也可以,但更冗长:

    lapply(seq_along(my.list), function(i)rep(my.list[[i]], repeat.list[[i]]))
    [[1]]
     [1] "a" "a" "a" "a" "a" "b" "b" "b" "b" "b" "b" "b" "c" "c" "c" "c" "c" "c" "d"
    
    [[2]]
    [1] "g" "g" "h" "h" "h"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-05
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      • 2021-05-19
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多