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

R语言中用case_when按列位置Mutate新列报错,求正确实现方法

在R中生成趋势箭头列的问题解决

数据框

首先给出你的数据框:

data <- structure(list(Category = c("Food", "Alcoholic B&T", "Clothing", 
"Housing", "Furnishings", "Health", "Transport", "Communication", 
"Recreation", "Education", "Hotels", "Misc", "All Items"), Weight = c(16.4, 
12.6, 3, 28.4, 5.5, 2, 14.3, 3.8, 3.6, 3.6, 1.4, 5.4, 100), `Apr 2022 (A)` = c(5.7, 
4.5, -2, 1.7, 7.7, 1.7, 18.9, -1.1, 4.4, 3.1, 9.3, 0.5, 5.6), 
    `May 2022 (F)` = c(7, 4.8, -1.6, 1.7, 7.8, 1.7, 19.3, -0.7, 
    4.7, 3.1, 9.1, 0.3, 6), `Jun 2022 (F)` = c(7.4, 5, -1.4, 
    1.7, 7.3, 1.8, 18.9, -0.2, 4.6, 3.1, 9.3, 0.5, 6.1), `Jul 2022 (F)` = c(7.7, 
    4.7, -1.5, 3.1, 7.4, 1.8, 18.4, -0.4, 4.2, 3.1, 8.8, 0.7, 
    6.4)), row.names = c(NA, -13L), class = c("tbl_df", "tbl", 
"data.frame"))

需求

要生成新列Trend,规则如下:

  • 当第6列(Jul 2022 (F))大于第3列(Apr 2022 (A))时,显示向上箭头\U2B08
  • 当第6列小于第3列时,显示向下箭头\U2B0A
  • 当两列相等时,显示横向箭头\U279E

原代码及报错

你之前的代码:

library(tidyverse)

data %>% 
mutate(Trend = case_when(.[,6] == .[,3] ~ "\U279E", 
                              .[,6] > .[,3] ~ "\U2B08", TRUE ~ "\U2B0A"))

报错信息:

Error in `mutate()`:
ℹ In argument: `Trend = case_when(...)`.
Caused by error in `case_when()`:
! `.[, 6] == .[, 3]` must be a vector with type <logical>.
Instead, it has type <logical[,1]>.

错误原因

因为你的数据框是tibble(tbl_df类),使用.[,6]提取列时返回的是单列tibble,而不是原子向量。case_when要求每个条件必须是逻辑向量,因此报错。

解决方案

方法1:用[[提取向量

tibble中[[n]]会直接提取对应列的原子向量,替换原来的.[,n]即可:

library(tidyverse)

data %>% 
  mutate(Trend = case_when(
    .[[6]] == .[[3]] ~ "\U279E", 
    .[[6]] > .[[3]] ~ "\U2B08", 
    TRUE ~ "\U2B0A"
  ))

方法2:直接使用列名(更推荐)

直接写列名可以避免列索引变化导致的错误,代码可读性更高:

library(tidyverse)

data %>% 
  mutate(Trend = case_when(
    `Jul 2022 (F)` == `Apr 2022 (A)` ~ "\U279E", 
    `Jul 2022 (F)` > `Apr 2022 (A)` ~ "\U2B08", 
    TRUE ~ "\U2B0A"
  ))

两种方法都能正确生成Trend列,满足你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:06:56