R programming, column reordering
1
4
Entering edit mode
9.5 years ago
MAPK ★ 2.1k

Hi Guys,

I have two data frames with thousands of columns. The dummy example looks like df1 and df2 below. All the columns names in df2 are in df1. Now, I want these two data frames to combined together in the order where the columns with the same columns names are together as shown in result. Thank you.

df1 <- data.frame(C1=c("A","H","C"),C2=c("0","0","0"), C3=c("A","C","D"),C4=c("A","V","G"))
df1

  C1 C2 C3 C4
1  A  0  A  A
2  H  0  C  V
3  C  0  D  G

df2 <- data.frame(C1=c("A","B","C"),C3=c("G","G","G"))
df2

C1 C3
1  A  G
2  B  G
3  C  G

Result

  C1 C1 C2 C3 C3 C4
1  A    A  0  A    G  A
2  H    B  0  C    G  V
3  C    C  0  D    G  G
R • 2.5k views
ADD COMMENT
7
Entering edit mode

​MAPK, you have asked a lot of R programming questions recently (examples of those that need to join/extract/compare multiple data tables):

You're welcome to ask R related questions here on biostars. However, I recommend to invest some time into learning R data manipulation tools:

This should help you to solve problems yourself. Also, you can try to ask R related questions on stackoverflow.com (most of your questions aren't bioinformatics specific, they are just general data structure manipulation problems). Further, it would be nice if you accept answers to your previous questions (if they helped you).

ADD REPLY
1
Entering edit mode
9.5 years ago
Brice Sarver ★ 3.8k

Assuming which goes where doesn't matter as long as they're grouped, this is pretty easy:

df3 <- cbind(df1, df2)
final <- df3[, order(names(df3))]
final

  C1 C1.1 C2 C3 C3.1 C4
1  A    A  0  A    G  A
2  H    B  0  C    G  V
3  C    C  0  D    G  G
ADD COMMENT
0
Entering edit mode

Sorry this didn't work for the large number of column names. Also, I want them in the same order.

ADD REPLY
1
Entering edit mode

brice.sarver's code should work for any number of column names. The result should have all the names in the same order with all the colnames of the later structure (in his code, it will be df2) be added with the ".1".

If that isn't what you needed, could you please elaborate on what you actually need?

ADD REPLY

Login before adding your answer.

Traffic: 1830 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