buhtz
buhtz

Reputation: 12152

Build names for variables/columns of a R data.frame

I have a data.frame with columns named like this

> names(df)
[1] "v1_1_a" "v1_1_b" "v1_2_a"

This is just an example of the nameing scheme. There are more columns with that naming scheme. I want to build the column names (of still existing columns) and do operations on them like this:

# pseudo code! python and R mixed
for minor in [1, 2, 3, 4, 5]:
    for letter in ['a', 'b', 'c', 'd']:
        col = 'v1_{}_{}'.format(minor, letter)
        df[col] <- df[col] * 10

Can I build variable names like that?

Tried for example: df[cat("v1_1_", "b", sep="")]

Upvotes: 0

Views: 47

Answers (1)

jasbner
jasbner

Reputation: 2283

Note* this is certainly not the best way to loop through a dataframe as mentioned in the comments below.

You can just paste the variables together and call the columns directly. Your pseudo code in R:

for(minor in c(1, 2, 3, 4, 5))
     for(letter in c('a', 'b', 'c', 'd'))
         df[,paste0('v1_',minor,'_',letter)] <- df[,paste0('v1_',minor,'_',letter)] *10

This doesn't work with your data frame because you don't have all the combinations. If you're unsure if the combination exists you can check for it before doing the calculations.

for(minor in c(1, 2, 3, 4, 5))
     for(letter in c('a', 'b', 'c', 'd'))
         if(paste0('v1_',minor,'_',letter) %in% colnames(df))
             df[,paste0('v1_',minor,'_',letter)] <- df[,paste0('v1_',minor,'_',letter)] *10

Upvotes: 1

Related Questions