简体   繁体   中英

How to mutate a column (part of) without using a formula in R

I want to replace those NA on column y by the vector subst <- c(5,6,7) . My result is out of order and also I think this is no the right way of doing what I want.

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)

We can use replace instead of ifelse as ifelse requires all arguments to be of same length

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

-output

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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