Home > Blockchain >  Looping through vector of variable names in R
Looping through vector of variable names in R

Time:11-15

I have the following data: Several groups of data with different sizes, e.g.,

a1 <- runif(2)
a2 <- runif(3)
a3 <- runif(2)
b1 <- runif(4)
c1 <- runif(6)
c2 <- runif(8)


a <- c("a1", "a2", "a3")
b <- c("b1")
c <- c("c1", "c2")

vars <- c("a", "b", "c")

I want to print each value of the variables (and do other things).

for (i in vars){
  for (j in i){
    print(j)
  }
}

My problem is that in the loop over vars, I only get the names of the variables, but I am not able to access them.

I tried also with *apply(.)

sapply(vars, function(df) {
  print(df)
})

and map(.)

vars %>% 
  map(~ print(.))

I still get only the names of the variables, but not the content.

One possible way could be to replace the variables in vars with the respective vector, i.e.

vars2 <- vars %>% [something]
vars2
[1] "a1" "a2" "a3" "b1" "c1" "c2"

and then loop through vars2.

I appreciate any help!

CodePudding user response:

The get() function will return the object when the parameter is the object name.

So:

for (i in vars){
    for (j in get(i)){
        print(get(j))
    }
}

[1] 0.9936563 0.5921018
[1] 0.326851258 0.669632069 0.009228891
[1] 0.6428064 0.1019502
[1] 0.8501049 0.7520931 0.3428727 0.3318866
[1] 0.7850959 0.3322788 0.5309424 0.8743996 0.7330708 0.1912109
[1] 0.1338074 0.6304955 0.7746226 0.3737855 0.2318912 0.3701741 0.4098900 0.6035598
  • Related