How can i handle variables like A1, A2,..., An in a loop? in R -
i have 10 different objects: a1, a2, ... a10. need make simple change each variable. such as
a1$x <- a1$x + 1 a2$x <- a2$x + 1 ... a10$x <- a10$x + 1
and
a1[,'new_x']<-cumprod(a1$x) a2[,'new_x']<-cumprod(a2$x) ... a10[,'new_x']<-cumprod(a10$x)
i'd shrink these codes using 'for' loop. tried
for(i in 1:10) { ai[,'new_x'] <- cumprod(ai$x) }
and of course not work. there way make work?
you can use looping approach without first converting objects single list or data frame if use eval()
function read objects , assign()
function write objects. example:
a1 <- data.frame(x=1:5) a2 <- data.frame(x=2:6) a3 <- data.frame(x=3:7) for(i in 1:3) { dfname <- paste0("a", i) df <- eval(parse(text=dfname)) df$new_x <- cumprod(df$x) assign(dfname, df) } a1
Comments
Post a Comment