R - 将 vectors/matix 作为行添加到另一个数据框

R - Adding vectors/matix as row to another dataframe

我以为我早就掌握了这项技能,但在这种情况下我一无所知,我只是收到错误消息。

这是同一个问题,但对我不起作用! How to add a named vector as a row to a data frame

我有这个数据框:

structure(list(AT2VI12 = 28, DENI011 = 27, GB0033R = 0, SE0004A = 2, 
SE0013R = 4), .Names = c("AT2VI12", "DENI011", "GB0033R", 
"SE0004A", "SE0013R"), row.names = c(NA, -1L), class = "data.frame")

>df
    AT2VI12 DENI011 GB0033R SE0004A SE0013R
1      28      27       0       2       4

现在我想添加这个第二个小数据框的第二列。

structure(list(x = c("AT2VI12", "DENI011", "GB0033R", "SE0004A", 
"SE0013R"), n = c(17L, 35L, 2L, 14L, 5L)), class = c("tbl_df", 
"tbl", "data.frame"), .Names = c("x", "n"), row.names = c(NA, 
-5L))

>df2
       x     n
    <chr> <int>
1 AT2VI12    17
2 DENI011    35
3 GB0033R     2
4 SE0004A    14
5 SE0013R     5

我这样做了:

df <- rbind(df, df2[,2])  # Error message: Not the same number of columns

然后我试了这个(想稍后删除额外的行)

df2 = t(df2)
df <- rbind(df, df2[2,]) # Error in match.names(clabs, names(xi)) 

还有这个:

rbind(df, as.data.frame(t(df2)))

我不知道怎么了。有人可以帮忙吗?

这是一个 tibble,无论您使用哪个索引,它总是 return 一个 tibble 因此您需要取消列出它以获取向量:

 rbind(df,unlist(df2[2]))
  AT2VI12 DENI011 GB0033R SE0004A SE0013R
1      28      27       0       2       4
2      17      35       2      14       5