我有一个看起来像这样的数据集:
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?我已经用粘贴功能尝试过这种语法,但没有用。
最佳答案
我们使用 unite
外mutate
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.
或者另一个选项是
transmute
与 str_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/