【问题标题】:Converting counts into individual observations [duplicate]将计数转换为单个观察值[重复]
【发布时间】:2021-03-10 16:26:59
【问题描述】:

在我看来,这似乎是一个简单的目标,但我正在努力寻找解决方案。

我的数据是这样排列的:

df <- data.frame(species = c("A", "B", "C"),
                 length= c(2, 3, 1),
                 count = c(4, 6, 1),
                 year=c(2008,2012,2008))
                
#  species length count  year
#1       A      2     4  2008
#2       B      3     6  2012
#3       C      1     1  2008

我想根据计数值复制行。所以我的数据集看起来像这样。当然,我不想删除除计数列之外的任何内容。

#  species length  year
#1       A      2  2008
#2       A      2  2008
#3       A      2  2008
#4       A      2  2008

我希望这是有道理的。

【问题讨论】:

    标签: r dplyr count data-manipulation


    【解决方案1】:
    library(dplyr)
    
    df %>%
      slice(rep(1:nrow(df), times = df$count)) %>%
      select(-count)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-29
      • 1970-01-01
      相关资源
      最近更新 更多