I have a massive dataset, and I want to add a factor to each value based on another factor. Currently, my data look like this:
Type Value
1 Wild 68.51
2 Wild 91.94
3 Captive 72.58
4 Hybrid 85.38
But I want to add another column of factors - {Australia, Costa Rica, Brazil} - that is based on if animals are wild, captive or hybrids. The data frame should then look like this:
Type Value Status
1 Wild 68.51 Costa Rica
2 Wild 91.94 Costa Rica
3 Captive 72.58 Australia
4 Hybrid 85.38 Brazil
Something like this using dplyr::case_when
?
library(dplyr);
df %>%
mutate(Status = case_when(
Type == "Wild" ~ "Costa Rica",
Type == "Captive" ~ "Australia",
Type == "Hybrid" ~ "Brazil"));
# Type Value Status
#1 Wild 68.51 Costa Rica
#2 Wild 91.94 Costa Rica
#3 Captive 72.58 Australia
#4 Hybrid 85.38 Brazil
df <- read.table(text =
"Type Value
1 Wild 68.51
2 Wild 91.94
3 Captive 72.58
4 Hybrid 85.38", header = T)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments