如何用R语言统计数据框指定数值列的数值出现频次?
R语言统计列中数值出现次数的方法
你可以用两种常用方法实现需求,得到指定格式的结果:
基础R原生方法
无需额外安装包,用table()函数统计频数后转成数据框并重命名列:
# 统计频数 count_result <- table(df$number_of_columns_with_text) # 转换为数据框并修改列名 result_df <- as.data.frame(count_result) colnames(result_df) <- c("number", "volume")
tidyverse工具包方法
如果习惯用dplyr的管道语法,代码更简洁:
# 先加载dplyr包(若未安装先运行 install.packages("dplyr")) library(dplyr) result_df <- df %>% count(number_of_columns_with_text, name = "volume") %>% rename(number = number_of_columns_with_text)
两种方法最终输出的结果都符合你要求的格式:
> result_df number volume 1 1 3 2 2 1 3 3 2
内容的提问来源于stack exchange,提问作者Erik Brole
相关产品推荐
相关产品推荐

