0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, I will try to follow your suggestion with sprintf and subsetting. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.