0

I have these 3 dataframes:

    df.1<-as.data.frame(matrix(rnorm(10),250,149))
    df.2<-as.data.frame(matrix(rnorm(10),250,149))
    df.3<-as.data.frame(matrix(rnorm(10),250,149))

I want to create another dataframe with these conditions:

the columns 1,4,7,10,...445 of df.4... will be the columns from df.1

the columns 2,5,8,11,...446 of df.4... will be the columns from df.2

the columns 3,6,9,12,...447 of df.4... will be the columns from df.3

In the ende my df.4 will have 3*149 columns.

How can I do this with dplyr package and its functions?

And most important, how can I mantain the names of my columns???

4
  • Do you really need three 250x149 (!) matrices to make your example reproducible? Commented Sep 25, 2018 at 1:23
  • @MauritsEvers :) no. It can be a smaller one. Because my original matrix has this dimensions Commented Sep 25, 2018 at 1:24
  • @RonakShah I edited the question. In the end my df.4 will have 3*149 = 447 columns Commented Sep 25, 2018 at 1:30
  • @李哲源 Im truly sorry. It wont happen again. Commented Sep 25, 2018 at 21:35

1 Answer 1

1

To do this we combine the dataframes with bind_cols() then reorder with select() as follows:

library (dplyr)
df.4 <- bind_cols(df.1, df.2, df.3)
# create the column order 
order <- c()
for(i in 1:149){
    temp <- c(i, i+149, i+298)
    order <- c(order, temp)
}
df.4 <- df.4 %>% select(order)

The loop used here is looping over numbers 1:149 and will not be slow regardless of the size of your data

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @Abdallah Atef but its not working. The original dataframes df.1, df.2 and df.3 all have 149 columns
No. It would ok a loop

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.