【问题标题】:Repeat values with a loop in R在 R 中循环重复值
【发布时间】:2016-01-05 16:56:53
【问题描述】:

我正在处理一个类似于下面的汇总数据集,我需要对其进行扩展,使其看起来像第二个数据集。

df <- data.frame(CustName = letters[1:3],
Years = c(4,2,1), 
MinYear = c(1995,1992,1998),
stringsAsFactors = F)

df

我尝试过使用循环,但没有成功

想要的输出是这样的

dfResult <- data.frame(CustName = rep(letters[1:3], c(4,2,1)),
Years = c(1995:1998, 1992:1993, 1998), stringsAsFactors = F)

dfResult

【问题讨论】:

    标签: r loops repeat


    【解决方案1】:

    您基本上需要按客户名称拆分数据集,然后根据每个客户的数据创建一个新的数据框。我们通过将 0:(Years-1) 添加到 startyear 来做到这一点。 -1 表示起始年份。最后,我们将它们绑定在一起。我们可以在 base-R 中做到这一点:

    res <- do.call(rbind,lapply(split(df,df$CustName),function(x){
      res <- data.frame(custName=x$CustName,
                        Year=x$MinYear+0:(x$Years-1))
      res
    }))
    
    # > res
    # custName Year
    # a.1        a 1995
    # a.2        a 1996
    # a.3        a 1997
    # a.4        a 1998
    # b.1        b 1992
    # b.2        b 1993
    # c          c 1998
    

    我们可以对 data.table 做同样的事情,让代码更具可读性:

    library(data.table)
    DT <- as.data.table(df)
    
    res <- DT[,.(Year=MinYear+0:(Years-1)),CustName]
    

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 1970-01-01
      • 2015-10-26
      • 2017-08-23
      • 2018-01-30
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多