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

R语言如何基于逗号分隔的features列统计数量生成新列

实现方案

方法1:tidyverse生态实现(推荐)

借助dplyr的mutate和stringr的str_count实现,逻辑简单易读:

# 加载依赖包
library(dplyr)
library(stringr)

# 假设你的原始数据框命名为df
df <- df %>%
  # 统计逗号数量+1即为特征总数,同步处理空值异常
  mutate(`Number of features` = case_when(
    is.na(features) | str_squish(features) == "" ~ 0,
    TRUE ~ str_count(features, ",") + 1
  ))

方法2:基础R实现(无需加载第三方包)

用原生函数实现相同逻辑:

# 假设你的原始数据框命名为df
df$`Number of features` <- sapply(gregexpr(",", df$features), function(x) {
  ifelse(x[1] == -1, 0, length(x)) + 1
})

原理说明

n个用逗号分隔的特征,中间会存在n-1个逗号,因此统计每行逗号的数量后加1,即可得到特征总数。上述两种方案都兼容空值、空字符串的异常场景,不会出现报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 09:57:03