在R语言中合并数据列并将数值置于括号内的实现方法
解决方案:合并颜色与对应数值为指定格式
首先还原你的原始数据集:
df <- 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"))
方法1:使用tidyverse工具链
适合处理tidy格式的数据,代码可读性强:
library(dplyr) library(stringr) result_df <- df %>% # 生成「颜色(数值)」格式的新列 mutate( col1 = str_glue("{x1}({x2})"), col2 = str_glue("{x3}({x4})") ) %>% # 只保留目标列 select(col1, col2) print(result_df)
方法2:Base R实现
无需加载额外包,适合轻量需求:
# 直接拼接字符串生成新列 df$col1 <- paste0(df$x1, "(", df$x2, ")") df$col2 <- paste0(df$x3, "(", df$x4, ")") # 提取目标列 result_df <- df[, c("col1", "col2")] print(result_df)
最终输出结果
两种方法都会得到如下格式的数据集:
# A tibble: 4 × 2 col1 col2 <chr> <chr> 1 red(60) blue(30) 2 green(10) red(30) 3 blue(50) red(40) 4 blue(50) green(30)
内容的提问来源于stack exchange,提问作者user19745561
相关产品推荐
相关产品推荐

