基本的R语言、dplyr和data.table不能合并包含数据框列的数据框:
x <- data.frame(a=1)
x$b <- data.frame(z=2)
y <- data.frame(a=3)
y$b <- data.frame(z=4)
# base and dplyr fail
rbind(x, y)
#> Warning: non-unique value when setting 'row.names': '1'
#> Error in `.rowNamesDF<-`(x, value = value): duplicate 'row.names' are not allowed
dplyr::bind_rows(x,y)
#> Error: Argument 2 can't be a list containing data frames
# data.table gives a result that doesn't make much sense to me
str(data.table::rbindlist(list(x,y)))
#> Warning in setDT(ans): Some columns are a multi-column type (such as a matrix
#> column): [2]. setDT will retain these columns as-is but subsequent operations
#> like grouping and joining may fail. Please consider as.data.table() instead
#> which will create a new column for each embedded column.
#> Classes 'data.table' and 'data.frame': 2 obs. of 2 variables:
#> $ a: num 1 3
#> $ b:'data.frame': 1 obs. of 2 variables:
#> ..$ : num 2
#> ..$ : num 4
#> - attr(*, ".internal.selfref")=<externalptr>
这段代码是由 reprex包(v0.3.0)于2020-01-03创建的。
我的预期输出是将数据框列绑定,从而得到类似下面的res
:
res <- data.frame(a= c(1,3))
res$b <- data.frame(z = c(3,4))
res
#> a z
#> 1 1 3
#> 2 3 4
str(res)
#> 'data.frame': 2 obs. of 2 variables:
#> $ a: num 1 3
#> $ b:'data.frame': 2 obs. of 1 variable:
#> ..$ z: num 3 4
我该如何解决这个问题?
res $ b <- data.frame(z = c(2,4))
? - Ali