Given a data frame df
like below
text <- "
model,var,value
M1,a,12211
M1,b1,10.21
M1,b2,5.07
M1,c1,41.8
M1,c2,58.2
M1,d,1.6
M2,a,11922
M2,b1,15.6
M2,b2,8.9
M2,c1,38.1
M2,c2,61.9
M2,d,1.8
M2,a,13101
M2,b1,9.21
M2,b2,6.56
M2,c1,36.07
M2,c2,63.93
M2,d,1.75
"
df <- read.table(textConnection(text), sep=",", header = T)
I want to add a col var2
based on the value of var
via dplyr mutate
.
Based on the following logic.
If var == 'b1'
or var == 'b2'
then All B
If var == 'c1'
or var == 'c2'
then All C
else var
I want to store the mapping as follows and use it to build the above logic
mapping <- c("All B"= list(c('b1', 'b2')), "All C" = list(c('c1', 'c2')))
> mapping
$`All B`
[1] "b1" "b2"
$`All C`
[1] "c1" "c2"
The expected output is
model var value var2
1 M1 a 12211.00 a
2 M1 b1 10.21 All B
3 M1 b2 5.07 All B
4 M1 c1 41.80 All C
5 M1 c2 58.20 All C
6 M1 d 1.60 d
7 M2 a 11922.00 a
8 M2 b1 15.60 All B
9 M2 b2 8.90 All B
10 M2 c1 38.10 All C
11 M2 c2 61.90 All C
12 M2 d 1.80 d
13 M2 a 13101.00 a
14 M2 b1 9.21 All B
15 M2 b2 6.56 All B
16 M2 c1 36.07 All C
17 M2 c2 63.93 All C
18 M2 d 1.75 d
I plan to use dplyr with an ifelse
as follows
df %>%
mutate(var2 = ifelse(# what should go here )
mapping
list included to dynamically pick up thevar2
values – user3206440case_when
: "Error: 'match' requires vector arguments". Have you seen this before ? Also, you are missing a trailing ")" for themutate
function. – steveb