【问题标题】:mutate and case_when assigns wrong valuemutate 和 case_when 分配了错误的值
【发布时间】:2019-06-23 23:12:15
【问题描述】:

我终其一生都无法弄清楚这段代码有什么问题。当frameNum 为1-63 时,代码分配anticipatory,但其他所有分配为NA

total_s2_data <- total_s2_data %>%
  mutate(frame_cat = case_when(
    frameNum == c(1:63, 120:193, 488:543, 580:625) ~ "anticipatory",
    frameNum == c(64:69, 194:219, 544:563, 626:653) ~ "phone",
    frameNum == c(70:193, 220:297, 564:625, 654:725) ~ "carryover",
    TRUE ~ NA)
  )

下面是可以复制的代码:

frameNum<- c(1:725)
total_s2_data <- as.data.frame(frameNum)

【问题讨论】:

  • 您的示例代码和数据给出了错误:“错误:必须是字符向量,而不是逻辑向量”。
  • 我怀疑你想要%in% 而不是==。喜欢 1:10 %in% 1:31:10 == 1:3
  • 还有NA_character_ 而不是NA
  • 或者更清楚地显示问题,比较10:1 %in% 1:3 vs 10:1 == 1:3

标签: r dplyr


【解决方案1】:

1. == 需要替换为 %in%,并且

2. NA 需要替换为 NA_character_

错误"Error: must be a character vector, not a logical vector"是由于第二次。

total_s2_data <- total_s2_data %>%
  mutate(frame_cat = case_when(
    frameNum %in% c(1:63, 120:193, 488:543, 580:625) ~ "anticipatory",
    frameNum %in% c(64:69, 194:219, 544:563, 626:653) ~ "phone",
    frameNum %in% c(70:193, 220:297, 564:625, 654:725) ~ "carryover",
    TRUE ~ NA_character_)
  )

 head(total_s2_data)
#   frameNum    frame_cat
#1        1 anticipatory
#2        2 anticipatory
#3        3 anticipatory
#4        4 anticipatory
#5        5 anticipatory
#6        6 anticipatory

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-08
    • 1970-01-01
    • 2023-03-05
    • 2020-03-29
    • 2021-05-30
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多