0
$\begingroup$

Let us say that we have some data frames named S1,S2,S3... that I want to join independently by column names to dataframe X. This is how they look like:

S1 <- data.frame(
  values = c (1:5), 
  numbers = c(11:15))
S1


S2 <- data.frame(
  values = c (1:5), 
  numbers = c(11:15))
S2


S3 <- data.frame(
  values = c (1:5), 
  numbers = c(16:20))
S3

#Dataframe X

X <- data.frame(
  values = c (26:30), 
  numbers = c(501:505))
X

S1
S2
S3
X

Using rbind, it is really easy to merge/join them according to column names. As below:

S1_X<- rbind(S1,X)

S1_X


S2_X<- rbind(S2,X)

S2_X


S3_X<- rbind(S3,X)

S3_X

Now the problem is that I have 500 plus data frames (S1,S2,S3,S4,S5.....S500) that I want to join to dataframe "X" by any function. For example rbind. Is it possible to use some loop/function for that.

What I have best tried is create a list (nested list of dataframes) that I can later split into individual dataframes:

output = lapply(list(S1=S1,S2=S2,S3=S3),rbind,X)

The output is what I expected. So it works The only problem is, how do I specify S1 to S500?

Thank you in advance!

$\endgroup$
3
  • $\begingroup$ Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. $\endgroup$
    – Community Bot
    Commented Sep 14, 2022 at 12:23
  • $\begingroup$ Hi, I did specify that I have 500 data frames named S1,S2,S3,S4.....S500 that I want to join to data frame X which is a dataframe too. If you will run the codes above you will find out that I tried to make it simple. Thank you! $\endgroup$
    – salman1490
    Commented Sep 14, 2022 at 12:49
  • $\begingroup$ @salman1490 I would recommend deleting this question here and reposting on Stack Overflow. It's not really as bioinformatics question and you'll get a much quicker response there. $\endgroup$
    – user438383
    Commented Sep 14, 2022 at 15:03

1 Answer 1

1
$\begingroup$

You can use For Loop here. Here I have created code using your algorithm, first created a list of merged dataframes and then split the list into separate dataframes.

S1 <- data.frame(values = c (1:5), numbers = c(11:15))
S2 <- data.frame(values = c (1:5), numbers = c(11:15))
S3 <- data.frame(values = c (1:5), numbers = c(16:20))
#Dataframe X
X <- data.frame(values = c (26:30), numbers = c(501:505))

#defining a NULL object
S=NULL
#creating a list of merged dataframes
for (i in 1:3){
S[i] = list(rbind(get(paste("S",i,sep='')),X))
names(S)[i] = paste("S",i,"_X",sep='')}

#extracting dataframes
for(i in 1:3){
assign(paste("S",i,"_X",sep = ""),S[[i]])
}
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.