我想使用for循环在R数据框中添加多个列

时间:2018-07-08 11:58:50

标签: r for-loop

我想添加名称为day2,day3到day19的列 我尝试了这段代码,但是没有用

for(i in 2:19)
{
    n=paste("day",i,sep="")
    mydata<-mutate(mydata,n=SMA(Price,i))
}

我将列名获取为n而不是n的值

2 个答案:

答案 0 :(得分:0)

假设您的data.frame是xdf

xnew <- paste("day", 1:19, sep="")
xdf[,c(xnew)] <- 0  # column type will be numeric. change to "" if you wish to make character
names(xdf)

你会得到这个

[1] "myid"  "myday" "myvol" "day1"  "day2"  "day3"  "day4"  "day5"  "day6"  "day7"  "day8"  "day9"  "day10" "day11" "day12" "day13" "day14" "day15" "day16"
[20] "day17" "day18" "day19"

答案 1 :(得分:0)

很高兴为您提供新的帮助。

请尝试以下操作:

library(TTR);
data(ttrc);

# Assume mydata is ttrc    
mydata = ttrc;

# SMA for 5 days - you can also loop it
n = paste("day",5,sep="")

# To assign to mydata use !!
mydata = mutate(mydata,!!n := SMA(Close,5) )