简体   繁体   English

R:case_when和dplyr mutate产生意外的“ NA”时

[英]R: case_when producing unexpected “NA” with dplyr mutate

I have the following user defined function 我有以下用户定义的功能

vareas1 <- function(a, b, c) {
  case_when(a == 1 ~ "top",
            b == 1 ~ "left",
            c == 1 ~ "right",
            near(a, 1/3) && near(b, 1/3) && near(c, 1/3) ~ "centre"
  )
}

test2 <- vareas1(1/3, 1/3, 1/3)

evaluates correctly to 正确评估

[1] "centre . [1] "centre

However, when applying it via mutate from dplyr, it sometimes produces NA. 但是,通过dplyr的mutate应用它时,有时会产生NA。 Example follows: 示例如下:

test1 <- data.frame("a" = c(1, 0, 0, 1/3),
                "b" = c(0, 1, 0, 1/3), 
                "c" = c(0, 0, 1, 1/3)) %>% mutate(area1 = vareas1(a, b, c))

This results in: 结果是:

          a         b         c area1
1 1.0000000 0.0000000 0.0000000   top
2 0.0000000 1.0000000 0.0000000  left
3 0.0000000 0.0000000 1.0000000 right
4 0.3333333 0.3333333 0.3333333  <NA>

The NA in line [4] instead of the result "centre" was unexpected and I do not understand where it comes from. 第[4]行中的NA而不是结果“中心”是意外的,我不知道它来自哪里。

I thought it may be due to the class of columns a, b and c and I adapted the function 我认为这可能是由于a,b和c列的类别所致,我修改了该功能

  vareas1_int <- function(a, b, c) {
            case_when(a == as.integer(1 * 10e6) ~ "top",
                      b == as.integer(1 * 10e6) ~ "left",
                      c == as.integer(1 * 10e6) ~ "right",
                      near(a, as.integer(1/3 * 10e+6) && 
                      near(b, as.integer(1/3 * 10e+6)) && 
                      near(c, as.integer(1/3 * 10e+6))) ~ "centre"
  )
}

and changed a, b, c to fitting integers: 并将a,b,c更改为合适的整数:

test1 <- test1 %>%
mutate(a_mil = as.integer(a * 10e+6),
     b_mil = as.integer(b * 10e+6),
     c_mil = as.integer(c * 10e+6))

But the oucome was the same: 但是结果是一样的:

      a         b         c area1    a_mil    b_mil    c_mil area_int
1 1.0000000 0.0000000 0.0000000   top 10000000        0        0      top
2 0.0000000 1.0000000 0.0000000  left        0 10000000        0     left
3 0.0000000 0.0000000 1.0000000 right        0        0 10000000    right
4 0.3333333 0.3333333 0.3333333  <NA>  3333333  3333333  3333333     <NA>

Thank you for your help! 谢谢您的帮助!

(This similar post doesn't cover my question.) (该类似帖子未涵盖我的问题。)

You need & instead of && in order to make your function work with vectors. 为了使函数与向量一起使用,您需要&而不是&&

library(tidyverse)

vareas1 <- function(a, b, c) {
  case_when(a == 1 ~ "top",
    b == 1 ~ "left",
    c == 1 ~ "right",
    near(a, 1/3) & near(b, 1/3) & near(c, 1/3) ~ "centre"
  )
}

data.frame("a" = c(1, 0, 0, 1/3),
  "b" = c(0, 1, 0, 1/3), 
  "c" = c(0, 0, 1, 1/3)) %>% mutate(area1 = vareas1(a, b, c))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM