Concatenating two text columns in dplyr

前端 未结 4 1635
渐次进展
渐次进展 2021-01-04 07:01

My data look like this:

round <- c(rep(\"A\", 3), rep(\"B\", 3))
experiment <- rep(c(\"V1\", \"V2\", \"V3\"), 2)
results <- rnorm(mean = 10, n = 6)
         


        
相关标签:
4条回答
  • 2021-01-04 07:15

    You could also try this:

    library(tidyr)
    library(dplyr)
    df = df %>% 
       unite(combined, round, experiment, sep = "_", remove = FALSE)
    

    The output will be:

    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
    

    This will retain your original columns.

    0 讨论(0)
  • 2021-01-04 07:18

    Another solution could be to use the stri_join function in stringi package.

    library(stringi)
    df$new = stri_join(df$round,df$experiment,sep="_")
    
    0 讨论(0)
  • 2021-01-04 07:26

    You can use the unite function from 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
    
    0 讨论(0)
  • 2021-01-04 07:31

    This should do the trick if you are looking for a new variable

    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 = "_")
    )
    
    0 讨论(0)
提交回复
热议问题