在 R 中用循环重复值
Repeat values with a loop in R
我正在处理一个类似于下面的汇总数据集,我需要对其进行扩展,使其看起来像第二个数据集。
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
您基本上需要按客户名称拆分数据集,然后根据每个客户的数据创建一个新的数据框。我们通过将 0:(Years-1) 添加到 startyear 来实现。 -1 是为了占 start-year。最后,我们将它们绑定在一起。我们可以在 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]
我正在处理一个类似于下面的汇总数据集,我需要对其进行扩展,使其看起来像第二个数据集。
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
您基本上需要按客户名称拆分数据集,然后根据每个客户的数据创建一个新的数据框。我们通过将 0:(Years-1) 添加到 startyear 来实现。 -1 是为了占 start-year。最后,我们将它们绑定在一起。我们可以在 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]