如何使用循环将多列添加到数据框

时间:2019-04-17 23:34:08

标签: r

我有一个包含2列的数据框,即“ dateperiod”和“ temp”,如下所示:-

dateperiod,temp
01/01/2019,20.995
02/01/2019,19.89
03/01/2019,17.68
04/01/2019,16.575
05/01/2019,12.155
06/01/2019,13.26
07/01/2019,16.575
08/01/2019,13.26
09/01/2019,19.89

对于指定的次数(例如n = 3),我希望能够创建6(n * 2)个列,如下所示:-

dateperiod,temp,temp_plus1,temp_plus2,temp_plus3,temp_minus1,temp_minus2,temp_minus3
01/01/2019,20.995,21.995,22.995,23.995,19.995,18.995,17.995
02/01/2019,19.89,20.89,21.89,22.89,18.89,17.89,16.89
03/01/2019,17.68,18.68,19.68,20.68,16.68,15.68,14.68
04/01/2019,16.575,17.575,18.575,19.575,15.575,14.575,13.575
05/01/2019,12.155,13.155,14.155,15.155,11.155,10.155,9.155
06/01/2019,13.26,14.26,15.26,16.26,12.26,11.26,10.26
07/01/2019,16.575,17.575,18.575,19.575,15.575,14.575,13.575
08/01/2019,13.26,14.26,15.26,16.26,12.26,11.26,10.26
09/01/2019,19.89,20.89,21.89,22.89,18.89,17.89,16.89

这样的想法是,三个“加”值列中的值是用“ n”表示的原始值,而三个“减”值列中的值是用“ n”表示的原始值,如下面的下部所示。桌子。

我无法找到一种循环方法(或使用任何Apply函数),因此我仅手动添加了这些列。但是,我想对“ n”值很高的大量添加列进行自动化。

任何建议将不胜感激。

最诚挚的问候

Deepak

2 个答案:

答案 0 :(得分:0)

使用cbind.data.frame()尝试lapply():

df_2 <- lapply(1:3, function(x) {
a <- df$temp + x
b <- df$temp - x
return(cbind.data.frame(a, b))
}, simplify = TRUE)

cbind.data.frame(df, df_2)

成为df,您的原始数据。然后,您可以根据需要重命名和订购滤芯。

希望有帮助

答案 1 :(得分:0)

purrr中,我们可以使用map_dfc创建新列

library(purrr) 
cbind(df, map_dfc(1:3, ~ list(df$temp + .x, df$temp - .x)))


#  dateperiod   temp     V1     V2     V3     V4     V5     V6
#1 01/01/2019 20.995 21.995 19.995 22.995 18.995 23.995 17.995
#2 02/01/2019 19.890 20.890 18.890 21.890 17.890 22.890 16.890
#3 03/01/2019 17.680 18.680 16.680 19.680 15.680 20.680 14.680
#4 04/01/2019 16.575 17.575 15.575 18.575 14.575 19.575 13.575
#5 05/01/2019 12.155 13.155 11.155 14.155 10.155 15.155  9.155
#6 06/01/2019 13.260 14.260 12.260 15.260 11.260 16.260 10.260
#7 07/01/2019 16.575 17.575 15.575 18.575 14.575 19.575 13.575
#8 08/01/2019 13.260 14.260 12.260 15.260 11.260 16.260 10.260
#9 09/01/2019 19.890 20.890 18.890 21.890 17.890 22.890 16.890