Reputation: 9018
I have a data frame and I'd like to use mutate to populate a "e_value" column that is the value for the "e" metric within a group so I use dplyr and group_by the group then mutate using value[metric == "e"] but this is returning an error when there is no metric == e within a group like in group C below. Is there a way to just return the f metric when there is no e metric?
library(dplyr)
# this code does not work because there is no e metric in group C
data =data.frame(group = c("A","A","B","B","C"),metric=c("e","f","e","f","f"),value = c(1,2,3,4,5))
data %>% group_by(group) %>% mutate( e_value = value[metric == "e"] )
## this code below work becuase there is always an e metric
data =data.frame(group = c("A","A","B","B"),metric=c("e","f","e","f"),value = c(1,2,3,4))
data %>% group_by(group) %>% mutate( e_value = value[metric == "e"] )
Upvotes: 0
Views: 10725
Reputation: 50668
Or like this using %in%
:
data %>% group_by(group) %>% mutate(e_value = ifelse("e" %in% metric, value, NA));
## A tibble: 5 x 4
## Groups: group [3]
# group metric value e_value
# <fctr> <fctr> <dbl> <dbl>
#1 A e 1 1
#2 A f 2 1
#3 B e 3 3
#4 B f 4 3
#5 C f 5 NA
Upvotes: 1
Reputation: 6264
You can insert an ifelse
to make it conditional.
data %>%
group_by(group) %>%
mutate(
e_value = ifelse(is.null(value[metric == "e"]), NA, value[metric == "e"])
)
# # A tibble: 5 x 4
# # Groups: group [3]
# group metric value e_value
# <fct> <fct> <dbl> <dbl>
# 1 A e 1.00 1.00
# 2 A f 2.00 1.00
# 3 B e 3.00 3.00
# 4 B f 4.00 3.00
# 5 C f 5.00 NA
Upvotes: 3