Create dataframe in R by selecting columns....but place the results by index

Viewed 191

I am trying to create a dataframe by selecting data from several dataframes...basically a simple SQL type exercise but with R. Sample data is created below. Dataframe A, and B. To select from both dataframes and create a new dataframe is straightforward such as:

AB<-data.frame(COLUMN1=A$ID, COLUMN2=B$ONE, COLUMNS3=B$TWO, COLUMN4=A$JOB, COLUMN5=B$THREE)

or selecting the data by an index instead of the column name as:

AB<-data.frame(COLUMN1=A[,1], COLUMN2=B$ONE, COLUMNS3=B$TWO, COLUMN4=A$JOB, COLUMN5=B$THREE)

What I actually need to do however is create a dataframe and instead of naming the new columns in "AB", I need to designate them by index so they are in the right order. I tried this as the following but it didn't work obviously. Any help would be appreciated

AB<-data.frame([,1]=A$ID, [,2]=B$ONE, [,3]=B$TWO, [,4]=A$JOB, [,5]=B$THREE)

SAMPLE DATA

A<-data.frame (ID=c("A", "B", "C"), CUSTOMER=c("1", "2", "3"), JOB=c("ONE", "TWO", "THREE"))

B<-data.frame (ONE=c("X", "Y", "Z"), TWO=c("10", "20", "30"), THREE=c("SMALL", "MEDIUM", "LARGE"))

1 Answers

I think @Dave2e has got it correct. You can select the columns from both the dataframe, cbind the result and order the dataframe. This can be done using column numbers or column names.

Using column numbers -

index1 <- c(1, 3)
index2 <- 1:3
res <- cbind(A[index1], B[index2])
res <- res[c(1, 3, 4, 2, 5)]
res

#  ID ONE TWO   JOB  THREE
#1  A   X  10   ONE  SMALL
#2  B   Y  20   TWO MEDIUM
#3  C   Z  30 THREE  LARGE

Using column names -

name1 <- c('ID', 'JOB')
name2 <- c('ONE', 'TWO', 'THREE')
res <- cbind(A[name1], B[name2])
res <- res[c('ID', 'ONE', 'TWO', 'JOB', 'THREE')]
res

Another option would be using select -

library(dplyr)
res <- bind_cols(A, B) %>% select(ID, ONE, TWO, JOB, THREE)
Related