I have a dataframe. I want to write condition for creating a column which depends on other column. Here it is:
tab <- tibble::tribble(
~dataset_id, ~type,
"Site4H", 268,
"Site4D", 479,
"SIte8H", 345,
"Site8D", 567,
"Site8K", blond507
)
library(dplyr)
tab %>%
mutate(state = case_when(
endsWith(dataset_id, "H") ~ "healthy",
endsWith(dataset_id, "D") ~ "disease",
TRUE ~ NA_character_
))
As you see column state equals healthy if value in column dataset_id ends with H. But i want it to be healthy for two cases: when value in column dataset_id ends with H and when value in column "type" starts with "blond". How could i do that? I need to use these exact functions, so solution with another libraries is not good.
Desired results is:
dataset_id type state
Site4H 268 healthy
Site4D 479 disease
SIte8H 345 healthy
Site8D 567 disease
Site8K blond507 healthy
tab <- tibble::tribble(
~dataset_id, ~type,
"Site4H", "268",
"Site4D", "479",
"SIte8H", "345",
"Site8D", "567",
"Site8K", "blond507"
)
tab %>%
mutate(state = case_when(
endsWith(dataset_id, "H") | startsWith(type, "blond") ~ "healthy",
endsWith(dataset_id, "D") ~ "disease",
TRUE ~ NA_character_
))
So you can simply add the type restriction to your case_when code which gives:
# A tibble: 5 x 3
dataset_id type state
<chr> <chr> <chr>
1 Site4H 268 healthy
2 Site4D 479 disease
3 SIte8H 345 healthy
4 Site8D 567 disease
5 Site8K blond507 healthy
Two notes:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.