R语言data.frame计算列百分比结果异常的解决方法
R数据框新增字段占比列的问题排查与解决
你写的占比计算逻辑本身没有问题,运行后得不到正确输出基本是以下几个高频原因,对应调整即可:
- 未将计算结果赋值回原数据对象
dplyr的管道操作不会直接修改原始数据,如果你只运行了带mutate的管道语句、没有写赋值,计算结果只会临时打印在控制台,不会保存到原数据框里。补全赋值即可:library(dplyr) # 记得先加载包,不然会报错找不到函数 data <- data %>% mutate(il.count.ratio = il.count.description / Words.count * 100, elle.count.ratio = elle.count.description / Words.count * 100, un.count.ratio = un.count.description / Words.count * 100) - 列名不匹配或字段类型错误
先运行colnames(data)核对列名,确认没有大小写错误、拼写错误(比如把Words.count写成Word.count);再运行str(data)检查参与计算的四列是不是数值型,如果是字符类型,除法运算会返回NA或报错,先转类型再计算:data <- data %>% mutate(across(c(il.count.description, elle.count.description, un.count.description, Words.count), as.numeric)) %>% mutate(il.count.ratio = il.count.description / Words.count * 100, elle.count.ratio = elle.count.description / Words.count * 100, un.count.ratio = un.count.description / Words.count * 100) - 如果后续要新增更多同类型占比列,不用逐列写计算式,可以用批量匹配写法减少重复代码:
# 自动匹配所有以count.description结尾的列计算占比,自动生成带ratio后缀的新列 data <- data %>% mutate(across(ends_with("count.description"), ~ .x / Words.count * 100, .names = "{.col}.ratio"))
用你提供的样例数据跑上述修正后的代码,计算结果完全符合预期:比如第一行il.count.ratio约为0.89,第二行elle.count.ratio约为3.08,第三行un.count.ratio为4,第四行il.count.ratio约为11.24。
内容的提问来源于stack exchange,提问作者Fella
相关产品推荐
相关产品推荐

