首页 > 解决方案 > looking for mutate_if, but for rows not columns

问题描述

I am looking for a way to mutate only certain rows of a dataframe based on two conditions. The first condition is always the same (x==1). The second is a recode() of specific values where the first condition is always met.

Here's a very simple version of what I have:

dat <- data.frame(x = c(1, 1, 2, 2),
                  y = c("a", "b", "a", "b"))

dat

#  x y
#1 1 a
#2 1 b
#3 2 a
#4 2 b

Here's what I want:

#  x y z
#1 1 a Apple
#2 1 b Banana
#3 2 a a
#4 2 b b

Nested ifelse statements work, but I have a lot of different y's to define, and I don't want to keep defining x.

dat %>%
  mutate(z = ifelse(x==1 & y=="a", "Apple",
             ifelse(x==1 & y=="b", "Banana", 
                    y)))

The following if() in the pipe does not work, but it's the type of idea I'm going for: when a certain condition is met, do some recoding. I have a lot of recoding to do in my actual use case, so looking for something efficient. I'm trying to do this in the middle of a long pipe that is not shown.

# DOES NOT WORK
dat %>%
  {if(x==1) 
    mutate(., 
           z = recode(y, 
                      "a" = "Apple",
                      "b" = "Banana")
           ) else 
    mutate(., z = y) 
  } 

标签: rdplyrmagrittr

解决方案


推荐阅读