1

I want to generate a dataframe, hminput, with 3 parameters from different smaller dataframes (named frqAFR, frqAMR, .. etc, as you can see below). So, instead of writing separately all the code to extract the three columns of each one and then bind them by column and after that by row, I was wondering if I could optimize it a bit with a for loop with strings from a list.

So, here is my idea so far:

listpop<-c("frqAFR","frqAMR","frqEUR","frqEAS","frqSAS","frqAFROURU","frqIND")


for (g in listpop) {
  hminput<- rbind(cbind(paste(g)["SNP"],paste(g)["POP"],paste(g)["MAF"]))
              }

But it generates a hminput dataframe with three NAs. Any thoughts? Thanks!

Desired output:

hminput

snp1 pop1 maf1
snp2 pop2 maf2
snp3 pop3 maf3
...
1
  • I didn't actually get what your input structure is like and what you are doing it in for-loop. However, I feel you need the hminput there in rbind. Something like , rbind(hminput, cbind(paste(g)..... ?? and I am sure there are more efficient and simple way to do this. Commented Jun 9, 2017 at 3:17

1 Answer 1

1

We need to get the value of the dataset objects. Assuming that the 'listpop' strings are the data.frame object names, get the values in a list using mget, then subset the columns "SNP", "POP", "MAF", and rbind the list elements

hminput <- do.call(rbind, lapply(mget(listpop), function(x) x[c("SNP", "POP", "MAF")]))

If we are using the for loop

hminput <- c()
for(g in listpop) {
     hminput <- rbind(hminput, get(g)[c("SNP", "POP", "MAF")])
}

If we are looking for efficient solution, then rbindlist from data.table can be used

library(data.table)
rbindlist(lapply(mget(listpop), `[`, c("SNP", "POP", "MAF")))

And if we need to use tidyverse

library(tidyverse)
mget(listpop) %>%
         map(~.[c("SNP", "POP", "MAF")] %>%
         bind_rows()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you , it worked !! :D I chose to use the first one.

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.