Search code examples
rdynamicrenamenaming

Dynamically change part of variable name in R


I am trying to automatise some post-hoc analysis, but I will try to explain myself with a metaphor that I believe will illustrate what I am trying to do.

Suppose I have a list of strings in two lists, in the first one I have a list of names and in the other a list of adjectives:

list1 <- c("apt", "farm", "basement", "lodge")
list2 <- c("tiny", "noisy")

Let's suppose also I have a data frame with a bunch of data that I have named something like this as they are the results of some previous linear analysis.

> head(df)
     qt[apt_tiny,Intercept]  qt[apt_noisy,Intercept]   qt[farm_tiny,Intercept]
1    4.196321                -0.4477012                -1.0822793
2    3.231220                -0.4237787                -1.1433449 
3    2.304687                -0.3149331                -0.9245896 
4    2.768691                -0.1537728                -0.9925387
5    3.771648                -0.1109647                -0.9298861
6    3.370368                -0.2579591                -1.0849262

and so on...

Now, what I am trying to do is make some automatic operations where the strings in the previous lists dynamically change as they go in a for loop. I have made a list with all the distinct combinations and called it distinct. Now I am trying to do something like this:

for (i in 1:nrow(distinct)){
var1[[i]] <- list1[[i]]
var2[[i]] <- list2[[i]]

#this being the insertable name part for the rest of the variables and parts of variable, 
#i'll put it inside %var[[i]]% for the sake of the explanation.

%var1[[i]]%_%var2[[i]]%_INT <- df$`qt[%var1[[i]]%_%var2[[i]]%,Intercept]`+ df$`qt[%var1[[i]]%,Intercept]`

}

The difficult thing for me here is %var1[[i]]% is at the same time inside a variable and as the name of a column inside a data frame.

Any help would be much appreciated.


Solution

  • You cannot use $ to extract column values with a character variable. So df$`qt[%var1[[i]]%_%var2[[i]]%,Intercept] will not work.

    Create the name of the column using sprintf and use [[ to extract it. For example to construct "qt[apt_tiny,Intercept]" as column name you can do :

    i <- 1
    sprintf('qt[%s_%s,Intercept]', list1[i], list2[i])
    #[1] "qt[apt_tiny,Intercept]"
    

    Now use [[ to subset that column from df

    df[[sprintf('qt[%s_%s,Intercept]', list1[i], list2[i])]] 
    

    You can do the same for other columns.