Use mutate inside for loop and write the results
1
0
Entering edit mode
14 months ago
poltora4enko ▴ 10

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 • 1.3k views
ADD COMMENT
0
Entering edit mode

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.

ADD REPLY
1
Entering edit mode
14 months ago
Basti ★ 2.0k

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)

ADD COMMENT

Login before adding your answer.

Traffic: 1603 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6