简体   繁体   English

通过选择列在 R 中创建 dataframe....但按索引放置结果

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

I am trying to create a dataframe by selecting data from several dataframes...basically a simple SQL type exercise but with R.我正在尝试通过从多个数据帧中选择数据来创建 dataframe ......基本上是一个简单的 SQL 类型的练习,但使用 R。 Sample data is created below.示例数据在下面创建。 Dataframe A, and B. To select from both dataframes and create a new dataframe is straightforward such as: Dataframe A 和 B. 从两个数据帧到 select 并创建一个新的 dataframe 很简单,例如:

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.然而,我实际上需要做的是创建一个 dataframe ,而不是在“AB”中命名新列,我需要按索引指定它们,以便它们按正确的顺序排列。 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"))

I think @Dave2e has got it correct.我认为@Dave2e 是正确的。 You can select the columns from both the dataframe, cbind the result and order the dataframe.您可以 select 来自 dataframe 的列, cbind结果并订购 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 -另一种选择是使用select -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM