Search code examples
rmember-variables

Function to extract variable values from data frame


I have R data.frame containing variable_name and variable_values. I'm writing a function to extract each variable_name and assign corresponding variable_values and keep it in memory for later use. However, I keep getting error message such as this "Error in as.name(df) <- df[i, 2] : could not find function "as.name<-" Can you please help ?

Example: df <- data.frame(name=c("Jane", "Bush","Bob", "Job"), age=c(12 , 34, 20, 50))

I want to assign each name its corresponding age like this.

Jane <- 12 Bush <- 34 Bob <- 20 Job <- 50

Here is code I started:

splitobs <- function(df){
for(i in 1:nrow(df)){
noquote(as.name(df[i, 1]) <- df[i, 2]
print()
   }
}

splitobs(df)enter code here

Solution

  • We set the names of 'age' with 'name', convert to list and use list2env to create multiple objects in the global environment (though not recommended).

     list2env(as.list(setNames(df$age, df$name)), envir=.GlobalEnv)
     Jane
     #[1] 12
    

    Or use assign in a for loop.

    for(i in 1:nrow(df)){
     assign(as.character(df$name[i]), df$age[i])
    }