当观测值的nr不同时,按列连接2个数据帧
如果列数不同,如何合并2个数据帧:当观测值的nr不同时,按列连接2个数据帧,r,dataframe,R,Dataframe,如果列数不同,如何合并2个数据帧: df1 structure: t1 t2 t3 0 0 0 1 1 1 1 1 1 1 1 1 df2 structure (has ZERO observations ): t1 t2 t3 t4 t5 输出: t1 t2 t3 t4 t5 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 0 样本数据: df1<-st
df1 structure:
t1 t2 t3
0 0 0
1 1 1
1 1 1
1 1 1
df2 structure (has ZERO observations ):
t1 t2 t3 t4 t5
输出:
t1 t2 t3 t4 t5
0 0 0 0 0
1 1 1 0 0
1 1 1 0 0
1 1 1 0 0
样本数据:
df1<-structure(list( t1=c(0,1,1,1), t2=c(0,1,1,1),t3 = c(0,1,1,1)), row.names = c(NA, 4L), class = "data.frame")
df2<-structure(list( t1=c(), t2=c(),t3 = c(),t4 = c(),t5 = c()), row.names = c(NA, 0L), class = "data.frame")
df1我们可以使用setdiff
查找存在于“df2”中而不存在于“df1”中的列名,并将这些列分配给“df1”中的0
df1[setdiff(names(df2), names(df1))] <- 0
另一个基本R选项可能使用合并
,例如
replace(out <- merge(df1,df2,all = TRUE),is.na(out),0)
更换(输出)
replace(out <- merge(df1,df2,all = TRUE),is.na(out),0)