首页 > 解决方案 > 如何在不使用 R 中的公式的情况下改变列(部分)

问题描述

我想用向量替换NA列上的那些。我的结果不正常,而且我认为这不是做我想做的事情的正确方法。ysubst <- c(5,6,7)

library(dplyr)
#> 
#> 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 <- tibble(x = c("a", "a", "b", "b", "b", "c", "c"),
             y = c(2, 3, NA, NA, NA, 1, 2))


subst <- c(5, 6, 7)

df2 <- df %>% mutate(y = ifelse(x == "b", subst, y))

# But I want to obtain
df3 <- tibble(x = c("a", "a", "b", "b", "b", "c", "c"),
             y = c(2, 3, 5, 6, 7, 1, 2))
Created on 2021-06-07 by the reprex package (v2.0.0)

标签: rdplyr

解决方案


我们可以使用replace而不是ifelseasifelse要求所有参数都相同length

library(dplyr)
df2 <- df %>%
      mutate(y = replace(y, x == 'b', subst))

-输出

df2
 df2
# A tibble: 7 x 2
  x         y
  <chr> <dbl>
1 a         2
2 a         3
3 b         5
4 b         6
5 b         7
6 c         1
7 c         2

推荐阅读