Transform variables in environment to data frame

Hi all, just switching to R from matlab and running into some begginner issues. I would appreciate your help:

I have a bunch of variables in my workspace that are not data frames. I want to convert them to data frames to use them in ggplot. I tried to do it with a for loop but couldn't get it. I understand the issue but not how to solve it. Here's the code that I tried

    #Listing all the variables
variables=ls()
#Removing the one that I don't want to transform
variables=variables[-c(1)]

#For loop to transform every variable into data.frame
for (value in variables)
{
  #Creating a new variable to keep "value" intact
  name=value
  
  name=data.frame(name)
  
}

Of course I am just creating a new dataframe that has one value, the variables name. Instead, I want to keep the content of the variable with the name of the variable but as a data frame

Thanks in advance

You can do it with eval:

variables <- ls()

# removing the one that I don't want to transform
variables <- variables[-1]

#For loop to transform every variable into data.frame
for (value in variables){	
	text <- paste(value, "<- data.frame(", value, ")")
	eval(parse(text=text))	
}
2 Likes

You can skip for loop altogether with a bit of rlang:

library(rlang)

a <- 2
b <- 3
c <- 4
d <- c(1, 2, 3)

variables <- ls()
variables <- variables[-c(1)]

tibble::tibble(!!!rlang::syms(variables))
#> # A tibble: 3 x 3
#>       b     c     d
#>   <dbl> <dbl> <dbl>
#> 1     3     4     1
#> 2     3     4     2
#> 3     3     4     3

Created on 2019-06-27 by the reprex package (v0.3.0)

However, I have to say that what you are doing is highly unidiomatic, so you'll probably have a better time with R if you learn a bit about how to do most common operations more "R-like".

One good book to learn it is https://r4ds.had.co.nz/. You can also take a look at "Advanced R" (https://adv-r.hadley.nz/). Don't be scared by "Advanced" in the name, just read first few chapters to get into the swing of things.

2 Likes

Thank you very much, exactly what I was looking for! :grinning:

1 Like

Thank you for your reply!! And also thanks for the resources. Will definetly take a look at them. I am aware that what I'm doing is also super inefficient so I'm working on improving my skills to get the most out of R. I recently read the paper on tidy data and I'm also practicing on datacamp.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.