使用dplyr创建基于均值分类的排序新列时遇R语言报错问题
问题描述
需要实现以下操作:
- 创建名为
Hello的新列,复制现有Engagement列的数据 - 将
Hello列按均值分为两类(8个高于均值、8个低于均值的数值) - 按分类结果排序
尝试使用dplyr包的mutate和arrange函数时失败,运行代码mutate (classe_df, Hello, Engagement)出现报错:
no applicable method for 'mutate' applied to an object of class "c('double', 'numeric')"
Engagement列由点赞数(Likes)除以浏览数(Vues)计算得到,共16个数值。完整代码如下:
Sujet <- sprintf("s_%d", 1:16) Titre <- c("Coffee cake cookies", "Poutine baloney", "Polite Boy","Infinity water glitch", "Garlic butter steak bites", "Sun Conure", "Pizza in my room", "Parkour skills", "Supercars", "Brown monster", "Batch of pasta", "Police grappler", "F340", "Ceramic brakes", "GT3 Seat Solution", "Over Priced GT2RS" ) Likes <- c(150700, 11200, 3500000, 256700, 1400000, 791300, 439900, 382700, 45400, 1300000, 246200, 32200, 319000, 1892, 3413, 17400) Vues <- c(1300000, 214500, 13500000, 11400000, 17100000, 6700000, 400000, 11300000, 203100, 18400000, 3000000, 1000000, 1800000, 12600, 23500, 213800) Engagement <- c(150700 / 1300000, 11200 / 214500, 3500000 / 13500000, 256700 / 11400000, 1400000 / 17100000, 791300 / 6700000, 439900 / 4000000, 382700 / 11300000, 45400 / 203100, 1300000 / 18400000, 246200 / 3000000, 32200 / 1000000, 319000 / 1800000, 1892 / 12600, 3413 / 23500, 17400 / 213800) classe_df <- data.frame(Sujet, Titre, Likes, Vues, Engagement) #install.packages("ggplot2") library(ggplot2) ggplot(classe_df, aes(x = Vues, y = Likes) ) + geom_point() + labs(x = 'Vues', y = 'Likes', title = 'Relation entre les likes et les vues') + theme_light() ggsave("ggplot.jpg", scale = 1, width = 10, height = 7, units = "cm", dpi = 300) #install.packages("dplyr") library(dplyr)
解决方案
报错原因
mutate(classe_df, Hello, Engagement)的语法不符合dplyr要求:
- dplyr的
mutate函数创建新列时,必须使用新列名=值的格式,当前写法未指定赋值关系,导致函数无法识别参数 - 错误的参数传递导致函数误将数值向量当成操作对象,触发类型不匹配报错
正确代码
使用dplyr管道语法完成所有需求:
# 执行列创建、分类、排序操作 classe_df <- classe_df %>% mutate(Hello = Engagement) %>% # 创建Hello列,复制Engagement数据 # 按均值创建分类列:高于/低于均值 mutate(engagement_group = ifelse(Hello > mean(Hello), "高于均值", "低于均值")) %>% # 先按分类排序(高于均值组在前),再按Hello值降序排列 arrange(desc(engagement_group), desc(Hello))
验证分类数量
执行以下代码确认两类各有8个数据:
table(classe_df$engagement_group)
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

