【问题标题】:How to duplicate column rows and fill an added column with one item in list in R如何复制列行并用R中列表中的一项填充添加的列
【发布时间】:2022-07-14 21:41:53
【问题描述】:

我有一个包含以下列的数据框:

tester <- data.frame(id = c(123456789, 987654321)) tester$furniture <- list(c("chair"), c("bed", "bench", "barstool")) tester$count <- c(1,3)

根据count列的值,每行重复[count]次:

tester[rep(seq_len(dim(tester_2)[1]), tester$count),]

家具清单中的物品数量将始终等于计数值

我想创建一个新列,其中包含列表中的一个项目,按从第一个到最后一个列表项的顺序排列。我会在这个新列中手动输入我想要的内容:

tester$new <- c("chair", "bench", "bed", "barstool"),但这现在不起作用,因为从上面的代码产生的数据帧在技术上只有两行。

任何建议将不胜感激!

【问题讨论】:

    标签: r string dataframe duplicates


    【解决方案1】:

    如果我理解正确,您可以使用lapply 选择列表的第一个元素,如下所示:

    tester <- data.frame(id = c(123456789, 987654321)) 
    tester$furniture <-  list(c("chair"), c("bed", "bench", "barstool")) 
    tester$count <- c(1,3)
    
    tester$new <- lapply(tester$furniture, `[[`, 1)
    tester
    #>          id            furniture count   new
    #> 1 123456789                chair     1 chair
    #> 2 987654321 bed, bench, barstool     3   bed
    

    reprex package (v2.0.1) 于 2022-07-14 创建

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多