R中是否可以使用for循环在现有数据框中创建新列并将值分配给新创建的列?
s_0133_AFE_Nr_Dr_CM['CM_2018001'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018001/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018002'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018002/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018003'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018003/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018004'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018004/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018005'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018005/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018006'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018006/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018007'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018007/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018008'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018008/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018009'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018009/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018010'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018010/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018011'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018011/s_0133_AFE_Nr_Dr_CM$Dr_2018001
s_0133_AFE_Nr_Dr_CM['CM_2018012'] = s_0133_AFE_Nr_Dr_CM$AFE_Cost_2018012/s_0133_AFE_Nr_Dr_CM$Dr_2018001
可以使用某些循环将其写成1行吗?请注意,我们正在通过创建新列来分配值。我尝试使用assing()函数,但它R在数据框架之外创建了新变量,而不是将其添加到同一数据框架中
答案 0 :(得分:1)
可以。只需沿着数字序列用paste0
分配多列即可:
s_0133_AFE_Nr_Dr_CM[paste0("CM_", 2018001:2018012)] <- s_0133_AFE_Nr_Dr_CM[paste0("AFE_Cost_", 2018001:2018012)]/s_0133_AFE_Nr_Dr_CM$Dr_2018001