You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在R中如何基于现有列按规则生成新的字符类型列?

解决方案

以下提供两种常用的实现方式:

方法1:使用tidyverse套件(dplyr+stringr,可读性更高)

library(dplyr)
library(stringr)

dfResult <- dfTest %>%
  mutate(newCol = if_else(
    condition = !is.na(var),
    true = str_c(var, " ≤ ", value),
    false = as.character(value)
  ))

注意:需要将value转为字符类型,保证新列所有值的数据类型统一,避免运行报错

方法2:Base R实现(无需加载额外依赖包)

dfTest$newCol <- ifelse(
  test = !is.na(dfTest$var),
  yes = paste0(dfTest$var, " ≤ ", dfTest$value),
  no = as.character(dfTest$value)
)

运行上述任意一种方法后,得到的结果如下:

> dfResult
     var value     newCol
1   milk     2   milk ≤ 2
2 coffee     7 coffee ≤ 7
3  honey     1  honey ≤ 1
4   <NA>     4          4
5  bread    10 bread ≤ 10

内容的提问来源于stack exchange,提问作者Electrino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:57:02