0

Why doesn't this code change actually change the column names of TEST?

TEST = data.frame(col1 = LETTERS, col2 = letters)
"TEST" %>% paste0(" %<>% dplyr::rename(capitalLetters = 'col1') ") %>% parse(text = .) %>% eval()

I want to do a series of transforms to a large number of dataframes, where I have a list of the names of the dataframe environmental variable names. But I don't want to manually type out the transform for each dataframe, so I thought to use parse text -> eval.

EDIT: getting rid of the assignment pipe

"TEST" %>% 
paste0(
    ., " <- ", ., 
    " %>% dplyr::rename(capitalLetters = col1) "
) %>% parse(text = .) %>% eval()

EDIT: Just noticed this doesn't work either

"A <- 3" %>% parse(text = .) %>% eval()
A
Error: object 'A' not found

I guess one cannot assign/update environmental variables through parse->eval?

Frank
  • 952
  • 1
  • 9
  • 23
  • by any chance you made a typo: `%<>%` instead of `%>%` ? – Antonios May 18 '21 at 15:14
  • not a typo, ```library(magrittr)```, this is a pipe which passes the input into the function on the right AND sets the input equal to the value of the function on the right – Frank May 18 '21 at 16:04
  • Updated to eliminate assignment pipe – Frank May 18 '21 at 16:45
  • `"TEST" %>% paste0(" %>% dplyr::rename(capitalLetters = 'col1') ") %>% parse(text = .) %>% eval()` doesn't work for you? – Antonios May 18 '21 at 16:49
  • It works, but it does not assign. The point of this is that I don't want to type the dataframe name TEST, I have a large list of dataframe names (list of environmental variable names of dataframes) all of which need a series of transformations. So I wanted the assignment to be part of the evaluated string. – Frank May 18 '21 at 17:00

1 Answers1

0

Not sure I have completely understand the problem. Hope this might help you

Dfs<-list(DF1=data.frame(col1 = LETTERS, col2 = letters),DF2=data.frame(col1 = LETTERS, col2 = letters))
DfsNew<-lapply(Dfs,function(x) x%>%rename(capitalLetters = 'col1'))

It will create a list with same data frame names and will change col1 to capitalLetters in all of them

Now if you want your dataframes to be in the global enviroment check this Return elements of list as independent objects in global environment

in our case

list2env(DfsNew,globalenv())
Antonios
  • 1,919
  • 1
  • 11
  • 18