合并R中带括号的两列内容

bqjvbblv  于 2023-03-05  发布在  其他
关注(0)|答案(4)|浏览(148)

我有一个数据集

structure(list(x1 = c("red", "green", "blue", "blue"), x2 = c(60, 
10, 50, 50), x3 = c("blue", "red", "red", "green"), x4 = c(30, 
30, 40, 30)), row.names = c(NA, -4L), class = c("tbl_df", "tbl", 
"data.frame"))

我想将每行的红色与60合并,蓝色与30合并,以此类推,这样就只有两列,如下所示

如何合并两列以及如何将数字放在括号中

ig9co6j1

ig9co6j11#

我相信glue::glue使我们在动态生成字符串时变得更容易,这样我们就可以避免对paste的多参数调用,就像paste(x, y, z ....)一样。我觉得它使我们更容易通过查看glue的参数来预测它的输出。

library(dplyr)
library(glue)

df %>% 
    mutate(x1 = glue("{x1} ({x2})"),
           x2 = glue("{x3} ({x4})"),
           .keep = 'none')

# A tibble: 4 × 2
  x1         x2        
  <glue>     <glue>    
1 red (60)   blue (30) 
2 green (10) red (30)  
3 blue (50)  red (40)  
4 blue (50)  green (30)
ia2d9nvy

ia2d9nvy2#

df %>% 
  mutate(x1 = paste0(x1, " (", x2, ")"),
         x2 = paste0(x3, " (", x4, ")")) %>% 
  select(x1, x2)

# A tibble: 4 × 2
  x1         x2        
  <chr>      <chr>     
1 red (60)   blue (30) 
2 green (10) red (30)  
3 blue (50)  red (40)  
4 blue (50)  green (30)
ars1skjm

ars1skjm3#

使用dplyover

library(dplyover)
library(dplyr)
df1 %>% 
  transmute(over(c(1, 3), ~ sprintf('%s (%d)', .("x{.x}"),
       .("x{.x+1}")), .names = "x{x_idx}"))
  • 输出
# A tibble: 4 × 2
  x1         x2        
  <chr>      <chr>     
1 red (60)   blue (30) 
2 green (10) red (30)  
3 blue (50)  red (40)  
4 blue (50)  green (30)
u59ebvdq

u59ebvdq4#

我知道Jilber Urbina已经回答了,但我想用R base在上面放两个硬币,这样就不需要使用其他包(如本例中的“dplyr”)。

# This is your data
df <- data.frame(x1 = c("red", "green", "blue", "blue"), 
               x2 = c(60, 10, 50, 50), 
               x3 = c("blue", "red", "red", "green"), 
               x4 = c(30, 30, 40, 30))
# foo is a function that returns "v1 (v2)", where "vi" is "variable i".
foo <- function(v1,v2) paste0(v1, " (",v2,")")
# let's use this function
df$x1 <- foo(df$x1,df$x2)
df$x3 <- foo(df$x3,df$x4)
# drop the other variables
df$x2 <- df$x4 <- NULL
#your expected data
> df
          x1         x3
1   red (60)  blue (30)
2 green (10)   red (30)
3  blue (50)   red (40)
4  blue (50) green (30)
> class(df)
[1] "data.frame"

相关问题