连接dplyr中的两个文本列
我的数据如下所示:连接dplyr中的两个文本列,r,dplyr,string-concatenation,R,Dplyr,String Concatenation,我的数据如下所示: round <- c(rep("A", 3), rep("B", 3)) experiment <- rep(c("V1", "V2", "V3"), 2) results <- rnorm(mean = 10, n = 6) df <- data.frame(round, experiment, results) > df round experiment results 1 A V1 9.782025 2
round <- c(rep("A", 3), rep("B", 3))
experiment <- rep(c("V1", "V2", "V3"), 2)
results <- rnorm(mean = 10, n = 6)
df <- data.frame(round, experiment, results)
> df
round experiment results
1 A V1 9.782025
2 A V2 8.973996
3 A V3 9.271109
4 B V1 9.374961
5 B V2 8.313307
6 B V3 10.837787
但是我得到了错误,
列名的长度必须是1(组大小),而不是6
。我还尝试了简单的base-R方法cbind(df,name\u mix)
,但收到一个类似的错误,告诉我df
和name\u mix
的大小不同。我做错了什么?您可以从tidyr
require(tidyverse)
df %>%
unite(round_experiment, c("round", "experiment"))
round_experiment results
1 A_V1 8.797624
2 A_V2 9.721078
3 A_V3 10.519000
4 B_V1 9.714066
5 B_V2 9.952211
6 B_V3 9.642900
如果您正在寻找一个新的变量,这应该可以实现
library(tidyverse)
round <- c(rep("A", 3), rep("B", 3))
experiment <- rep(c("V1", "V2", "V3"), 2)
results <- rnorm(mean = 10, n = 6)
df <- data.frame(round, experiment, results)
df
df <- df %>% mutate(
name = paste(round, experiment, sep = "_")
)
库(tidyverse)
round另一个解决方案是在stringi包中使用stri_join函数
library(stringi)
df$new = stri_join(df$round,df$experiment,sep="_")
您也可以尝试以下方法:
library(tidyr)
library(dplyr)
df = df %>%
unite(combined, round, experiment, sep = "_", remove = FALSE)
输出将是:
combined round experiment results
A_V1 A V1 10.152329
A_V2 A V2 10.863128
A_V3 A V3 10.975773
B_V1 B V1 9.964696
B_V2 B V2 9.876675
B_V3 B V3 9.252936
这将保留原始列。使用new\u df%mutate(name=paste0(round,“\u”,experiment))
。但是如果我复制/粘贴了你的代码,我就无法重现这个错误。你确定某个地方没有打字错误吗?@MrFlick我根本没有收到错误消息,所以有点困惑。。。也许更新dplyr
?疯狂地检查我的代码(来自IRL,而不是上面的示例),以防输入错误,所以我认为不是这样。使用unite
,如下所示,似乎是可行的。这或unite
建议可能就是答案。非常感谢。
combined round experiment results
A_V1 A V1 10.152329
A_V2 A V2 10.863128
A_V3 A V3 10.975773
B_V1 B V1 9.964696
B_V2 B V2 9.876675
B_V3 B V3 9.252936