Here is a simple dataset:
mydf <- tibble(country = rep(c("UK", "US"), each = 3),
date = rep(c("Day1", "Day2", "Day3"), times = 2),
cases = seq(1:6))
# A tibble: 6 x 3
country date cases
<chr> <chr> <int>
1 UK Day1 1
2 UK Day2 2
3 UK Day3 3
4 US Day1 4
5 US Day2 5
6 US Day3 6
I want to create a new column called "part_us" using mutate()
where TRUE is displayed if the value in "country" is equal to "US" and FALSE if it's anything other than "US".
It's a simple task but I am still learning R and would be grateful for some help with this.
You can use ifelse()
inside mutate()
on your dplyr
pipeline:
library(dplyr)
#Data
mydf <- tibble(country = rep(c("UK", "US"), each = 3),
date = rep(c("Day1", "Day2", "Day3"), times = 2),
cases = seq(1:6))
#Code
mydf <- mydf %>% mutate(part_us=ifelse(country=='US',T,F))
Output:
# A tibble: 6 x 4
country date cases part_us
<chr> <chr> <int> <lgl>
1 UK Day1 1 FALSE
2 UK Day2 2 FALSE
3 UK Day3 3 FALSE
4 US Day1 4 TRUE
5 US Day2 5 TRUE
6 US Day3 6 TRUE
Another way can be next: (Many thanks and credits to @Qwethm):
#Code 2
mydf <- mydf %>% mutate(part_us=country=="US")
Same output.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加