Search code examples
rtidyverserecode

How to recode several values for a specific row tidyverse


I would like to find a way to change values in several columns for a specific row using tidyverse. For example, with base R and the iris dataset:

iris[iris$Sepal.Length == 5.1, c("Petal.Length",
                                 "Petal.Width")] <- c(1.5,
                                                      0.5)

So far, I found this with tidyverse, but how to change these values for only the row where Sepal.Length == 5.1? I know I could filter the row that I want and then change the values, but what if I want to keep the whole dataset as in the base example above?:

myiris <- iris %>% 
 mutate_at(c("Petal.Length","Petal.Width"),
 funs(recode(., "1.4" = 1.5, "0.2" = 0.5)))

Thank you!


Solution

  • Maybe this would work, it's not the most elegant, but it worked for me:

    library(tidyverse)
    
    myiris <- iris %>% 
      mutate_at(c("Petal.Length","Petal.Width"),
          funs(ifelse(Sepal.Length == 5.1, c(1.5, 0.5), c(Sepal.Length, Sepal.Width))))