Home > OS >  R: Using variable name and output in for loop
R: Using variable name and output in for loop

Time:09-01

I have four timeseries and what I want to do is to get the logarithm from each one in a for-loop. I could do it individually but there's no fun in that.

So I got:

db$M1 <- c(1,2,3,4,5)
db$M2 <- c(1,2,3,4,5)
db$M3 <- c(1,2,3,4,5)
db$M4 <- c(1,2,3,4,5)

M1 <- ts(db$M1, start = c(1995, 12), frequency = 12)
M2 <- ts(db$M2, start = c(1995, 12), frequency = 12)
M3 <- ts(db$M3, start = c(1995, 12), frequency = 12)
M4 <- ts(db$M4, start = c(1995, 12), frequency = 12)

and what i've tried is:

AM <- list(M1, M2, M3, M4)
for(x in AM) {
assign(paste0("log_", x), log(x))
}

Of course that doesn't work, also tried parse() with no luck

Bonus points if you can help me loop the M# <- ts(...)

Thanks

CodePudding user response:

dplyr's across with everything() or alternatively starts_with("M") can do the mutations all in one step, all you have to do afterwards is print.


df <- db %>%
  mutate(across(everything(), ~log(ts(., start = c(1995, 12), frequency = 12))))

for (i in 1:ncol(df)) {
  print(colnames(df)[i])
  print(df[[i]])
}


# [1] "M1"
#            Jan       Feb       Mar       Apr May Jun Jul Aug Sep Oct Nov       Dec
# 1995                                                                     0.0000000
# 1996 0.6931472 1.0986123 1.3862944 1.6094379                                      
# [1] "M2"
#            Jan       Feb       Mar       Apr May Jun Jul Aug Sep Oct Nov       Dec
# 1995                                                                     0.0000000
# 1996 0.6931472 1.0986123 1.3862944 1.6094379                                      
# [1] "M3"
#            Jan       Feb       Mar       Apr May Jun Jul Aug Sep Oct Nov       Dec
# 1995                                                                     0.0000000
# 1996 0.6931472 1.0986123 1.3862944 1.6094379                                      
# [1] "M4"
#            Jan       Feb       Mar       Apr May Jun Jul Aug Sep Oct Nov       Dec
# 1995                                                                     0.0000000
# 1996 0.6931472 1.0986123 1.3862944 1.6094379

Data:

db <- data.frame(M1 = c(1,2,3,4,5),
                  M2 = c(1,2,3,4,5),
                  M3 = c(1,2,3,4,5),
                  M4 = c(1,2,3,4,5))

CodePudding user response:

Using lapply()

#Your data for reproduce:
db<- list(M1=c(1,2,3,4,5),
                M2 = c(1,2,3,4,5),
                M3=c(1,2,3,4,5),
                M4=c(1,2,3,4,5))

#To get your AM list
AM <- lapply(db,function(x) ts(x, start = c(1995, 12), frequency = 12))

#To get your logAM list and rename
logAM <- lapply(AM,function(x) log(x))
names(logAM) <- paste0("log_",names(logAM))
  • Related