Sowmya S. Manian
Sowmya S. Manian

Reputation: 3833

r binding data frames in different combinations in for loop

I have generated 10 data frames S1 to S10. Now I want to create 10 more data frames T1 to T10 using S1 to S10 in different combinations. Each T Sets will have 9 of the S Sets.

Example,

T1 = rbind(S2,S3,S4,S5,S6,S7,S8,S9,S10)   # If T1 is the set, S1 should not be there.    
.  
.  
.   
T10 = rbind(S1,S2,S3,S4,S5,S6,S7,S8,S9)  # T10 not there.

How Can I generate T1 to T10 using for loop, assuming S1 to S10 data frames is provided with equal number of columns and headers are same through out S1 to S10.

Any help is highly appreciated. If not for loop, suggest any other function.

Thank You.

Upvotes: 0

Views: 52

Answers (1)

lukeA
lukeA

Reputation: 54237

Here's one way

S1 <- data.frame(x=1)
S2 <- data.frame(x=2)
S3 <- data.frame(x=3)

lst <- mget(grep("S\\d+", ls(), value = TRUE))
idx <- combn(1:length(lst), length(lst)-1)[, length(lst):1]
res <- apply(idx, 2, function(x) {
  do.call(rbind, lst[x])
})
names(res) <- paste0("T", 1:length(lst))
list2env(res, .GlobalEnv)

apply uses a loop under the hood.

Upvotes: 2

Related Questions