yumba
yumba

Reputation: 1096

R: How to access a variable which name has been created on the fly (with paste)

I'm wondering how to create a variable name (of a variable that already exist) using paste and then access this variable.

Example:

var<-c("A","B","C")

for (i in 1:3){
     paste0("var")[i] 
}

Note: Assume, that I need to use paste0 to create the variable name (I'm dealing with data.frames and use paste0 to create the variables for the different columns)

Thanks!

EDIT:

Alright, here's the bigger picture: I have two data frames: smallDF and bigDF. I want to copy data from bigDF to smallDF. Matching is done with the user_name.

user <- c("userA","userB","userC")
variables<-c("user_age","user_city","user_street")

for (t in 1:length(variables)){

  for (j in 1:length(user)){

    x<-paste0("bigDF$",variables[t])
    y<-paste0("smallDF$",variables[t])

    tmp<-unique(x[which(bigDF$user_name==user[j])])[1] # unique will only yield one entry
    replace<-c(as.character(rep(tmp,length(y[which(smallDF$user_name==user[j])]))))
    y[which(smallDF$user_name==user[j])]<-replace

  }
}

The code above does not work. However, when I avoid the first for-loop and replace x and y with the respective variable names (bigDF$user_age etc) everything works. That's why I thought there must be a simple way of creating those variable names on the fly with the outer for-loop. Thanks everybody!

Upvotes: 2

Views: 1439

Answers (2)

alap
alap

Reputation: 647

Solution:

    dat <- eval(parse(text="paste0"))

in dat you have the output.

Upvotes: 0

Greg Snow
Greg Snow

Reputation: 49640

First look at the help ?"[[" then possibly at fortune(312). The problem is that somewhere along the line you learned about the magical $ shortcut without properly learning about what it is a shortcut for and feel that you need to use the shortcut in cases where it is the longest distance between 2 points (kind of like using a shortcut between New York City and Boston when trying to get from London to Paris).

If you use code like bigDF[[ variables[t] ]] instead of trying to use $ then that will access the column of bigDF with the name currently in variables[t].

Learn to use [[ and other subsetting properly (only use $ where appropriate) and your whole process will be greatly simplified.

Upvotes: 3

Related Questions