[英]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.frame
和data.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.