I have a dataset in which I am wanting to change the word in the variable
column based on the values in column b
.
So, the intent is that when the value of b
is not equal to 0
change the corresponding values of Variable
from a
to b
.
How can I do this?
Sample Data:
structure(list(a = c(1, 2, 3, 4, 5, 0, 0, 0, 0, 0), b = c(0,
0, 0, 0, 0, 23.5, 24.5, 28.6, 12, 17), Variable = c("a", "a",
"a", "a", "a", "a", "a", "a", "a", "a")), class = "data.frame", row.names = c(NA,
-10L))
Desired output:
structure(list(a = c(1, 2, 3, 4, 5, 0, 0, 0, 0, 0), b = c(0,
0, 0, 0, 0, 23.5, 24.5, 28.6, 12, 17), Variable = c("a", "a",
"a", "a", "a", "b", "b", "b", "b", "b")), class = "data.frame", row.names = c(NA,
-10L))
Code:
library(tidyverse)
df = df %>%
mutate(Variable = if_else(b != 0, "b", Variable)) # Not using the right syntax stuck...
Error in `mutate()`:
! Problem while computing `Variable = if_else(b != 0, "b", Variable)`.
Caused by error in `if_else()`:
! `false` must be length 10 (length of `condition`) or one, not 29232.
CodePudding user response:
df %>%
mutate(Variable = ifelse(b > 0, "b", Variable))