Search code examples
rglobal-variablesvariable-assignmentassignassignment-operator

Assign is not working as expected when recoding data frame variables?


I've been having an issue where I've been trying to recode many variables at once. What seemed the easiest way to do things was to use assign and place the variable in .GlobalEnv. I now see that it's not even working outside of the function.

Does anyone have any idea why,

assign('dataframe$col1', 3 - dataframe$col1, env = .GlobalEnv)

seems to have no effect on dataframe$col1?


Solution

  • Using assign, this can be done in a complicated way

     assign('dataframe', `[[<-`(dataframe, 'col',
                  value = 3- dataframe$col), envir=.GlobalEnv)
    
     dataframe$col
     #[1]  2  1  0 -1 -2
    

    Less complicated and safer would be

     dataframe$col <- 3-dataframe$col
    

    Or if you are using data.table

     library(data.table)
     setDT(dataframe)[, col:= 3- col] 
    

    and the dplyr/magrittr option is

     library(dplyr)
     library(magrittr)
     dataframe %<>%
             mutate(col = 3 - col)
    

    data

     dataframe <- data.frame(col= 1:5)