0

I want to add columns with names day2, day3 up to day19 I tried this code but it is not working

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

I get the column name as n instead of the value of n

L_J
  • 2,351
  • 10
  • 23
  • 28
  • 2
    Welcome to Stack Overflow. Please [format your code](https://meta.stackexchange.com/a/22189/371738) appropriately. In addition [provide example data](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) in order to make your issue reproducible. – jay.sf Jul 08 '18 at 12:01

2 Answers2

0

let's say your data.frame is 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)

you will get this

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

Happy to help given you are new to SO.

Please try below:

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) )
MSW Data
  • 441
  • 3
  • 8