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

R语言使用if-else语句为dataframe添加新列报错及优化咨询

问题原因
  • R 基础语法中的普通if-else为标量判断逻辑,仅支持单个布尔值作为判断条件。你传入的counties$Series_Complete是和数据行数等长的向量,直接作为判断条件会触发长度不匹配警告,且最终只会取第一个元素的判断结果赋值给calc,无法实现逐行分类的需求。
  • 你在管道操作中调用mutate生成新列后,没有将结果回存到counties变量,即使逻辑无问题也不会修改原数据。
最优实现方案

推荐使用dplyr内置的case_when函数实现多条件向量判断,完全适配你的分类逻辑,代码更简洁易读:

#set working directory
setwd("C:/Users/weirc/OneDrive/Desktop/Undergrad Courses/Fall 2021 Classes/GHY 3814/final project/data")

#load packages
library(readr)
library(dplyr)

#load data
counties <- read_csv("vaxData_counties.csv")

# 直接逐行判断生成class新列,结果回存到counties
counties <- counties %>% 
  mutate(class = case_when(
    Series_Complete >= 75 ~ 4,
    Series_Complete >= 50 ~ 3,
    Series_Complete >= 25 ~ 2,
    TRUE ~ 1
  ))

如果你偏好使用基础R实现,也可以用cut函数完成分箱操作:

counties$class <- cut(
  counties$Series_Complete,
  breaks = c(-Inf, 25, 50, 75, Inf),
  labels = c(1, 2, 3, 4),
  right = FALSE
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:24:03