我想找到一个干净,高效的创建一个新的变量与5个现有变量的复杂计算。我的问题是,一个变量是一个因素,另外四个包含NAs。更好的方法来计算新的变量从复杂的计算多个变量,一些神经网络
我有一个数据集的具有以下结构的变量几组:
- expenditure_period - 为其1 =每日,2 =每周3 = 月,4 =每年
- expenditure1因子 - 整数,金额花在每天期间
- expenditure2 - 整数,花费金额为每周期
- expenditure3 - 整数,花费金额按月周期
- expenditure4 - 整数,量花费每年周期
对于每一行/观察,只有4个整数的一个字段取决于expenditure_period的值具有的数值外,其余均为的NA。
例如:
expenditure_period expenditure1 expenditure2 expenditure3 expenditure4
1 monthly NA NA 5 NA
2 weekly NA 5 NA NA
3 monthly NA NA 2 NA
4 monthly NA NA 5 NA
5 monthly NA NA 58 NA
我想创建一个包含标准每月支出一个新的变量。所以如果支出周期是每日支出1 * 30。如果每周,那么支出2 * 4。如果每月,那么支出3 * 1。如果每年,然后expenditure4/12
最好的解决方案,我能想出如下烂摊子:
data$expenditure_factor[data$expenditure_period=="daily"] <- 30
data$expenditure_factor[data$expenditure_period=="weekly"] <- 4
data$expenditure_factor[data$expenditure_period=="monthly"] <- 1
data$expenditure_factor[data$expenditure_period=="yearly"] <- 1/12
data$expenditure_month <- apply(data[,c("expenditure1", "expenditure2",
"expenditure3", "expenditure4", "expenditure_factor")], 1,
function(x) { sum(x[1:4], na.rm=TRUE) * x[5]})
我尝试添加在一起expenditure1,2,3,4使用+运算符,但这导致所有新辅助因3个新辅助个数增加1个。我尝试使用rm.na的sum函数创建一个临时变量,但这导致每行的总和相同。我试图从dplyr包中使用mutate,没有任何效果。
有没有更简单,更优雅的方式来做到这一点?我必须对大约12种不同的支出类别进行同样的处理。我很抱歉,如果之前已经询问过,我找不到类似的线索。如果已经有人请指导我。
我在Windows 7
如果您的示例很容易重现,并且您也显示了期望/预期的结果,那将会更好。这里有一些指导:http://stackoverflow.com/a/28481250/1191259 – Frank
使用'switch'的''apply'语句'switch' –