Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当观测值的nr不同时,按列连接2个数据帧_R_Dataframe - Fatal编程技术网

当观测值的nr不同时,按列连接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

如果列数不同,如何合并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<-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)