【问题标题】:Concatenating two text columns in dplyr连接 dplyr 中的两个文本列
【发布时间】:2018-11-23 12:32:05
【问题描述】:

我的数据如下所示:

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

我有一个不同的数据集,它将与这个数据集合并,其中roundexperiment 的每个组合都是一个唯一的行值,即"A_V1"。所以我真正想要的是一个变量name,它将两列连接在一起。然而,这在 dplyr 中比我预期的更难做到。我试过了:

name_mix <- paste0(df$round, "_", df$experiment)
new_df <- df %>%
  mutate(name = name_mix) %>%
  select(name, results)

但我得到了错误,Column name must be length 1 (the group size), not 6。我还尝试了 cbind(df, name_mix) 的简单 base-R 方法,但收到类似的错误,告诉我 dfname_mix 的大小不同。我做错了什么?

【问题讨论】:

  • 使用new_df &lt;- df %&gt;% mutate(name=paste0(round, "_", experiment))。尽管如果我复制/粘贴您的代码,我将无法重现该错误。你确定没有错别字吗?
  • @MrFlick 我根本没有收到错误消息,所以有点困惑......也许更新dplyr
  • 检查了我的代码(来自 IRL,而不是上面的示例),因为拼写错误,所以我不认为是这样。如下所示,使用unite 似乎可行。

标签: r dplyr string-concatenation


【解决方案1】:

您可以使用tidyr 中的unite 函数

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

【讨论】:

    【解决方案2】:

    如果您正在寻找新变量,这应该可以解决问题

    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 = "_")
    )
    

    【讨论】:

    • 无论是这个还是unite 的建议,都可能是答案。谢谢!
    【解决方案3】:

    你也可以试试这个:

    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
    

    这将保留您原来的列。

    【讨论】:

      【解决方案4】:

      另一种解决方案是使用 stringi 包中的 stri_join 函数。

      library(stringi)
      df$new = stri_join(df$round,df$experiment,sep="_")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-01
        • 2022-01-27
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多