【问题标题】:Recode variables with ifelse and is.na使用 ifelse 和 is.na 重新编码变量
【发布时间】:2021-08-24 09:47:21
【问题描述】:

我想根据另一个不是 NA 的变量重新编码一个变量。在下面的示例中,每次new_name 不是 NA 时,我都想用new_name 替换name。我想这很简单,但是我在示例中尝试的解决方案不起作用。感谢您的帮助。

df <- structure(list(id = c(321, 452, 564, 678), name = c("Red", "White", "Black", "Blue"), 
                new_name = c("Pink", NA, NA, "Light blue")), row.names = c(NA, -4L), 
                class = c("tbl_df", "tbl", "data.frame"))

ifelse(is.na(df$new_name), 
       df$name == df$new_name, 
       df$name == df$name)

【问题讨论】:

  • 1.请更正您共享的数据,缺少报价。 2. 列名是new_name,但您在尝试中使用的name_new 不存在。 3. 你在尝试ifelse(is.na(df$new_name), df$new_name, df$name) 吗?

标签: r


【解决方案1】:

您忘记在示例数据中关闭引号。 这是case_when 的工作示例。 我选择case_when 而不是ifelse 并没有什么特别的原因,但是如果你有多个条件,它会更容易构建。

还请注意,与您的示例代码相比,如果 name_newNAname 将被分配 name_new,如果我正确解释了您的意图,则与您在文本中描述的相反。

library(dplyr)
#> Warning: package 'dplyr' was built under R version 4.0.3
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- structure(list(id = c(321, 452, 564, 678), name = c("Red", "White", "Black", "Blue"), 
                new_name = c("Pink", NA, NA, "Light blue")), row.names = c(NA, -4L), 
                class = c("tbl_df", "tbl", "data.frame"))


df %>% 
  mutate(name = case_when(
    !is.na(new_name) ~ new_name,
    !is.na(name) ~ name
  ))
#> # A tibble: 4 x 3
#>      id name       new_name  
#>   <dbl> <chr>      <chr>     
#> 1   321 Pink       Pink      
#> 2   452 White      <NA>      
#> 3   564 Black      <NA>      
#> 4   678 Light blue Light blue



# Alternative solution with `coalesce` (suggested by Martin Gal in comments)
df %>% 
  mutate(name = coalesce(name, new_name))
#> # A tibble: 4 x 3
#>      id name  new_name  
#>   <dbl> <chr> <chr>     
#> 1   321 Red   Pink      
#> 2   452 White <NA>      
#> 3   564 Black <NA>      
#> 4   678 Blue  Light blue

reprex package (v0.3.0) 于 2021 年 8 月 24 日创建

【讨论】:

  • 非常感谢!当new_name 丢失时,您将如何保留原始name?我的失败尝试是df %&gt;% mutate(name = case_when(!is.na(new_name) ~ new_name, is.na(new_name) ~ name))
  • @Jasper 看看dplyrcoalesce函数
  • @Jasper,这是我的疏忽。我已经编辑了我的答案,包括case_when 的解决方案和使用 Martin 的建议。
  • @mhovd 非常感谢,它运行良好!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-07
  • 2020-10-27
  • 2020-05-31
  • 1970-01-01
  • 1970-01-01
  • 2017-11-19
  • 1970-01-01
相关资源
最近更新 更多