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
相关产品推荐
相关产品推荐

