This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Use mutate inside for loop and write the results

Dear colleagues,

I would like to figure out how to use loops to work with dataframes.

The specific task for example is this: I have, lets say, 9 dataframes and I want to apply the mutate function to all of them, that is, add a column and save the result in the same dataframes. What am I doing:

I already have dataframes in my environment

Then to go through them I create a list from them:

dflist <- list(m1, m12, m13, m14, m2, m3, m5, m6, m7)

then I do this loop:

for (i in 1:length(dflist)){
  dflist[[i]] <- dflist[[i]] %>% 
    mutate(symbol = rownames(.))
}

For some reason, the dataframes change only inside the list that I created, but the dataframes themselves that I had do not change. I understand that I have to use paste somehow, but I don’t know how. Please tell me how to write the results from the cycle into dataframes, maybe I should access dataframes inside the cycle in a different way? I would be grateful if you could help me understand how to do this both through the for loop and through lapply function.

r dplyr

This isn't really a bioinformatics question but your code should modify each of your dataframes in your list of dataframes, so I'm not sure exactly what problem you are running into.

1 answer

You are modifying the list (the dataframes inside the list) which is different from the individual dataframes outside the list. If you want to obtain the individual dataframes outside the list back in your environment, you need : list2env(dflist,.GlobalEnv)

Log in to answer this question.