粘贴数据框而不更改为因子水平

Paste data frame without changing into factor levels

我有如下向量 a,b,c,d:

 a <- c(1,2,3,4)
 b <- c("L","L","F","L")
 c <- c(11,22,33,44)
 d <- c("Y", "N", "Y","Y")

然后我尝试使用粘贴来获得此输出 (1):

paste(a,b,c,d, sep = "$", collapse = "%")
[1] "1$L$Y%2$L$N%3$F$Y%4$L$Y"

那我改成这样,假设df:

df <- data.frame(a,b,c,d)

并获得此输出 (2):

paste(df, sep = "$", collapse = "%")
[1] "c(1, 2, 3, 4)%c(2, 2, 1, 2)%c(11, 22, 33, 44)%c(2, 1, 2, 2)"

我的问题是: (1) 有人可以向我解释为什么在 df 中它将其元素更改为数字吗? (2) 有没有其他方法可以使用 df 获取输出 (1)?

这是您使用的方法的替代方法:

df_call <- c(df, sep="$")
paste(do.call(paste, df_call), collapse="%")

[1] "1$L$Y%2$L$N%3$F$Y%4$L$Y"

Demo

您不能在此处直接将 paste 应用于您的案例的数据框,要获得所需的输出,您需要在两个级别应用 paste

paste(apply(df, 1, function(x) paste(x, collapse = "$")), collapse = "%")

#[1] "1$L$Y%2$L$N%3$F$Y%4$L$Y"

其中 apply 命令创建一个行向量

apply(df, 1, function(x) paste(x, collapse = "$"))
#[1] "1$L$Y" "2$L$N" "3$F$Y" "4$L$Y"

和下一个 paste 命令将这些与 collapse 参数合并为“%”。

paste 在其 ... 参数上运行 as.character (或内部类似的东西),有效地解析列表。看看

as.character(df)
# [1] "c(1, 2, 3, 4)"     "c(2, 2, 1, 2)"     "c(11, 22, 33, 44)" "c(2, 1, 2, 2)"    
deparse(df$a)
# [1] "c(1, 2, 3, 4)"

您的代码正在将这些值粘贴在一起。要解决此问题,您可以使用 do.call.

do.call(paste, c(df, sep = "$", collapse = "%"))
# [1] "1$L$Y%2$L$N%3$F$Y%4$L$Y"

这是一个 dplyr 方法:

pull(summarise(unite(df, tmp, 1:ncol(df), sep="$"), paste(tmp, collapse="%")))

或者:

df %>%
  unite(tmp, 1:ncol(df),sep="$") %>%
  summarise(output = paste(tmp, collapse="%")) %>%
  pull()