r - 联合返回错误 'no applicable method for ' 联合 _' applied to an object of class "c ('double' , 'numeric' )"

标签 r

我有一个看起来像这样的数据集:

p = c(3, 4, 5, 6, 7)
q = c("fr", "", "fr", "fe", "fre")
b = c(1, "", 1, "", 1)
a = c("r", "f", "b", "m", "p")

df=data.frame(p, q, b, a)

我想将q、b和a联合起来,并将结果放在一个新列中,所以我使用了unite:
new_df <- df %>% 
  mutate(Merged = unite(q,b,a), sep = "_")

我收到此错误:

Error in UseMethod("unite_") :
no applicable method for 'unite_' applied to an object of class "c('double', 'numeric')"



另外,与上述问题无关,我如何指定 范围 代码中的列,这样我就不必手动输入所有列(我想合并数十列)。我可以写吗q:a对于列 q 到 a?我已经用粘贴功能尝试过这种语法,但没有用。

最佳答案

我们使用 unitemutate

library(dplyr)
library(tidyr)

df %>% 
     unite(Merged, q, b, a, sep= "_")
unite的用法是

unite(data, col, ..., sep = "_", remove = TRUE, na.rm = FALSE)



在哪里

col - The name of the new column, as a string or symbol.



或者另一个选项是 transmutestr_c
library(stringr)

df %>%
    transmute(p, Merged = str_c(q, b, a, sep="_"))

关于r - 联合返回错误 'no applicable method for ' 联合 _' applied to an object of class "c ('double' , 'numeric' )",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59885169/

相关文章:

r - 如何为 R 中的变量分配固定内存大小

r - 如何使用网格图形系统将剖面线应用于多边形?

R包ReporteRs : how to let it show cell padding in generated . docx文档?

具有独特组合的 R tcrossprod

r - 使用匹配行上的另一个数据帧更新数据帧,例如使用 join 语句进行 SQL 更新

r - 函数将 n 个整数除以 app.大小相同

regex - 使用 Regex 修改 CSV 中的特定列

r - 加载与安装库的语法。

r - 在最新版本的 rgl 软件包中,legend3d 功能不起作用

使用 R 和 dplyr 按列名替换许多列的值