【问题标题】:R - Adding vectors/matix as row to another dataframeR - 将向量/矩阵作为行添加到另一个数据帧
【发布时间】:2018-07-15 19:34:18
【问题描述】:

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

这是同一个问题,但它对我不起作用! 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)))

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

【问题讨论】:

    标签: r dataframe error-handling rbind


    【解决方案1】:

    这是一个tibble,无论您使用哪种索引,它都会返回一个tibble,因此您需要取消列出它以获得一个向量:

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

    【讨论】:

    • 啊,好吧!谢谢你。我永远不会自己解决这个问题。
    • 很高兴它有帮助。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-03-12
    • 1970-01-01
    • 2016-12-25
    • 2021-09-13
    • 1970-01-01
    • 2014-07-06
    • 2018-03-09
    • 2016-02-19
    相关资源
    最近更新 更多