简体   繁体   English

R-如何将数据框的列添加为另一个数据框的列?

[英]R - How to add column of data frame as column of another data frame?

I have 2 data frames, the dimensions are like this: 我有2个数据框,尺寸如下:

dim (df1)
[1] 1418    1

dim (df2)
[1] 1418    1

So I only have 1 column in each DF and the same number of rows. 因此,每个DF中只有1列,并且行数相同。 I want to add the 2nd data frame to the first one so that I have a dim of 1418 rows and 2 columns. 我想将第二个数据帧添加到第一个数据帧,以使我有1418行和2列的暗淡。

I did this: 我这样做:

df1[,2] = df2[,1] # and this:
dfnew = merge (df1, df2)

But it doesnt work. 但它不起作用。 Any idea how to do it? 知道怎么做吗?

The merge function requires that you have a shared column between the data.frame s that you're combining. merge功能要求您要合并的data.frame之间有一个共享列。 In your case, with only one column each, this couldn't possibly be the case. 在您的情况下,每列只有一列,就不可能是这种情况。

As @Lyngbakr noted in the comments, you want to use cbind which will literally concatenate the two together. 就像@Lyngbakr在评论中指出的那样,您想使用cbind它将字面地将两者连接在一起。 For example, dfnew = cbind(df1,df2) 例如, dfnew = cbind(df1,df2)

cbind will work on vectors, data.frame and data.frame like objects as well as matrices. cbind可以处理矢量, data.framedata.frame类的对象以及矩阵。

df1$addl_col<-df2$col

This should work as long as the lengths are the same (which is implied by nrow(df1)==nrow(df2) 只要长度相同(nrow(df1)== nrow(df2)暗示)

You can also use dplyr, which has advantages of performance and chaining (and avoids some redundant syntax). 您还可以使用dplyr,它具有性能和链接优势(并避免了某些冗余语法)。 Two options: 两种选择:

df<-mutate(df,addl_col=df2$'col')
df<-df%>%mutate(addl_col=df2$'col')

Although this is a bit unorthodox for dplyr, as seen by the necessity of the quotation marks. 尽管这对于dplyr来说有点不合常规,但从引号的必要性可以看出。

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

相关问题 如何在R中的数据框中添加列 - How do add a column in a data frame in R R 在另一个数据框中逐列选择数据框中的列 - R Selecting column in a data frame by column in another data frame 将一个数据帧的列添加到另一个类似数据帧的列 - Add a column of one data frame to a column of another similar data frame 如何根据R中另一列的值将数据帧中的列数据添加到语料库? - How to add data from column in a data frame to a corpus based on a value from another column in R? 如何基于另一列在R数据框中对列进行排名 - How to rank column in r data frame based on another column 在R中,如何根据第一列的内容向数据帧添加一列? - In R, how to add a column to a data frame based on the contents of the first column? 在 R 的 data.frame 中的另一列下方添加一列 - Add one column below another in a data.frame in R 如何将一列与另一列的出现次数一起添加到data.frame - how add a column to a data.frame with the occurence number of an another column 如何根据另一列中的部分字符串向 R 中的数据框添加一列? - How do I add a column to a data frame in R based on a partial string in another column? 将数据帧列与另一数据帧R中的单行相乘 - Multiply a data frame column with a single row in another data frame, R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM