How to modify the values of specific rows while keep the whole data frame using dplyr?

As you know, the filter will subset the data frame. However, if I want to keep the whole data frame and modify part of it, besides the base method dataframe[condition, "column"] <- values, how could I achieve this using dplyr?

I found some good solutions from here as follows:

  1. mutate + ifelse
suppressMessages(library(dplyr))
z <- data.frame(w = c("a", "a", "a", "b", "c"), x = 1:5, y = c("a", "b", "c", "d", "e"), 
                stringsAsFactors=FALSE)
z
#>   w x y
#> 1 a 1 a
#> 2 a 2 b
#> 3 a 3 c
#> 4 b 4 d
#> 5 c 5 e

z %>% 
  mutate(y = ifelse(w == "a" & x == 2, 9, y))
#>   w x y
#> 1 a 1 a
#> 2 a 2 9
#> 3 a 3 c
#> 4 b 4 d
#> 5 c 5 e
  1. mutate + replace
suppressMessages(library(dplyr))
z <- data.frame(w = c("a", "a", "a", "b", "c"), x = 1:5, y = c("a", "b", "c", "d", "e"), 
                stringsAsFactors=FALSE)
z
#>   w x y
#> 1 a 1 a
#> 2 a 2 b
#> 3 a 3 c
#> 4 b 4 d
#> 5 c 5 e

z %>% mutate(y = replace(y, w=="a" & x==2, 9),
             y = replace(y, w=="a" & x==3, NA))
#>   w x    y
#> 1 a 1    a
#> 2 a 2    9
#> 3 a 3 <NA>
#> 4 b 4    d
#> 5 c 5    e

z %>% mutate(y = y %>% 
               replace(w=="a" & x==2, 9) %>% 
               replace(w == "a" & x == 3, NA))
#>   w x    y
#> 1 a 1    a
#> 2 a 2    9
#> 3 a 3 <NA>
#> 4 b 4    d
#> 5 c 5    e

I think this "subset-assignment" operation is quite useful, but I didn't find the standard (official) document about it in dplyr. Are there any other good solutions and recommendations?

Many thanks for your kind guidance :slightly_smiling_face:

Here is a possible workflow

library(dplyr)
library(tibble)
z <- data.frame(w = c("a", "a", "a", "b", "c"), x = 1:5, y = c("a", "b", "c", "d", "e"), 
                stringsAsFactors=FALSE) 

z <- rownames_to_column(z)

row_to_change <- 2

#alter row 2 
(z_change <- slice(z,row_to_change))
(z_dontchange <- slice(z,-row_to_change))

#do whatever
(z_change <- mutate(z_change, x=9,y="X"))


(new_z <- bind_rows(z_change,z_dontchange) %>% arrange(rowname))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Get it. Thanks @nirgrahamuk. Good idea.