且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在R中使用mutate函数时出现错误消息

更新时间:2022-04-30 10:05:18

使用Make212和Renu,这是修复它的一种选择:

Using comments by Make212 and Renu, here's one option for fixing it:

library(dplyr)
mutate(x,
       perfLev = case_when(
         SS <  1438              ~ "Below Basic",
         SS >= 1439 & SS <= 1499 ~ "Basic",
         SS >= 1500 & SS <= 1545 ~ "Proficient",
         SS >= 1546              ~ "Advanced",
         TRUE                    ~ "huh?"
       ) )

我添加了一个默认值( TRUE ),通常很好(显式代码)。请注意,如果您不包含 TRUE ,则它将获得 NA 值,以防万一, 。如果满足以下任何条件,我就会在这里看到它发生:

I added a "default" (TRUE), which is generally good (explicit code). Note that if you do not include the TRUE, then it would get an NA value, in case that's what you want. I can see it happening here if any of the following are true:


  • is.na(SS)

  • SS> = 1438& SS < 1439

  • SS> 1499年SS < 1500

  • SS> 1545年SS < 1546

  • is.na(SS)
  • SS >= 1438 & SS < 1439
  • SS > 1499 & SS < 1500
  • SS > 1545 & SS < 1546

如果 NA 您可能不需要它>是可以接受的,并且您保证具有 SS 的完整性。

You may not need it if NA is acceptable and you are guaranteed of SS's integrality.

此代码相当于对您的代码进行了轻微修复:

This code is equivalent to a slight fix to your code:

mutate(x,
       perfLev = 
         ifelse(SS < 1438, "Below Basic",
                ifelse(SS >= 1439 & SS <= 1499, "Basic",
                       ifelse(SS >= 1500 & SS <= 1545, "Proficient",
                              ifelse(SS >= 1546, "Advanced", "huh?"))))
       )

仅用于样式/清晰度的缩进。

Indentation for style/clarity only.