r - 使用循环或 IF 函数根据条件在数据框中添加值 - 在 R 代码中
问题描述
我有一个数据,其中每个帐号都有每月现金余额。但是,为每个帐户 ID 提供数据的记录数或月数是不同的,比如有些有 12 个月的数据,有些有 24 个月的数据等等。我必须将所有数据放入 ARIMA 模型并预测下个月的余额。我注意到 ARIMA 模型不适用于不均匀的时期,或者它会产生不寻常的结果。
`Account_id Month $ balance
A 201901 100
A 201902 120
A 201903 135
B 201903 20
C 201902 1700
C 201903 1400
` 我试图通过修改 excel 中的数据集来添加缺失月份的行,并在余额中设置零值,从而导致所有帐户具有相同数量的记录和月份。
我想通过 R 代码执行此手动步骤。我相信这应该是一些循环 / IF 函数或 Rbind/cbind 的东西,但对代码不是那么流利。请帮忙!
根据建议的解决方案,我尝试了这个:
每个 id 每月生成 54 行,所有余额显示为 0
months <- as.character(seq(as.Date('2015-01-
01'),as.Date('2019-06-01'), by = "1 month"))
accounts <- df$account_id
shell <- expand.grid(Account_id = accounts, Month = months, stringsAsFactors
= F)
data <- data.frame(Account_id = df$account_id, Month =
df$partition_ledger_year_month, balance = df$amount_usd,stringsAsFactors = F)
df2 <- merge(shell, data, by=c('Account_id','Month'), all.x = T)
df2[which(is.na(df2$balance)),]$balance <- 0
预期输出:
`Account_id Month $ balance
A 201901 100
A 201902 120
A 201903 135
B 201901 0
B 201902 0
B 201903 20
C 201901 0
C 201902 1700
C 201903 1400
所有值都在我的数据框列中,只有我必须缺少余额为“0”的飞蛾。任何帐户 ID 的完整数据为 54 个月。
解决方案
如何制作一个余额为零的 shell data.frame,然后填写您拥有的余额:
# All Possible Months
months <- as.character(seq(as.Date('2019-01-01'),as.Date('2020-01-01'), by = "1 month"))
# All Possible account ids
accounts <- LETTERS
# A shell
shell <- expand.grid(Account_id = accounts, Month = months, stringsAsFactors = F)
# Your data
data <- data.frame(Account_id = c('A','B','A'), Month = c('2019-02-01', '2019-03-01','2019-01-01'), balance = c(100,200,300),stringsAsFactors = F)
# Left Join to the shell
df <- merge(shell, data, by=c('Account_id','Month'), all.x = T)
# Fill in missing balances
df[which(is.na(df$balance)),]$balance <- 0
df