I have a variable named Tactic (migratory tactics for a predatory species of fish) that contains three levels i.e "Migr", "OcRes", "EstRes" see data below:
combo1 <- structure(list(Sex = c("F", "M", "F", NA, "M", "F", NA, NA, "M",
"F", NA, "M", "F", "F", NA, "F", "F", NA, "M", "F", NA, "M",
"F", "F", "F", "F", "F", "M", NA, "F", "M", "M", "F", "F", "M",
"F", NA, NA, NA, NA, NA, NA, "F", "F", NA, NA, NA, "M", "F",
"F", NA, "F", "F", NA, NA, "M", "F", NA, "F", NA, "M", NA, "F",
NA, NA, NA, NA, "F", "M", "M", NA, "F"), Tactic = c("Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "Migr", "OcRes", "Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "OcRes", "Migr", "Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr",
"Migr", "EstRes", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr", "Migr",
"Migr", "Migr", "Migr", "EstRes", "Migr", "Migr", "Migr", "EstRes",
"Migr", "OcRes", "Migr", "EstRes", "Migr", "Migr", "Migr", "Migr",
"Migr", "Migr", "Migr", "Migr", "Migr", "Migr")), class = "data.frame", row.names = c(NA,
-72L))
I want to reduce the data for 5-year-olds from 2018 only, and create a new column with EstRes (Estuary) and OcRes (Ocean Residents) renamed as Resident, and all others renamed as Migratory; so I can then plot and compare the average lengths (cm) of Residents versus Migrants. I think I am close but not quite there. Any assistance would be greatly appreciated.
avlen<-combo1 %>%
filter(Age_Year%in%5) %>%
filter(Sample.Year%in%2018) %>%
droplevels() %>%
mutate(TacticB = case_when(Tactic = EstRes ~ Resident, Tactic = OcRes ~ Resident, TRUE ~ 'Migratory'))
group_by(TacticB) %>%
summarise(avlen=mean(Length_cm), stdev=sd(Length_cm))
avlen
This is edited in from the comment:
avlen <-combo1 %>% filter(Age_Year%in%5) %>%
filter(Sample.Year%in%2018) %>% droplevels() %>%
mutate(TacticB = case_when(Tactic == "EstRes" ~ Resident,
Tactic == "OcRes" ~ Resident,
TRUE ~ as.character("Migratory"))%>%
group_by(TacticB) %>%
summarise(avlen=mean(Length_cm), stdev=sd(Length_cm))%>%
avlen # and the editor is guessing that final `%>%` is not correct.
CodePudding user response:
Do you mean this? I'm not sure that your sample data do not including many variables.
combo1 %>%
filter(Age_Year == 5, Sample.Year == 2018) %>%
mutate(TacticB = ifelse(Tactic %in% c("EstRes", "OcRes"), "Resident", "Migratory")) %>%
group_by(TacticB) %>%
summarise(avlen=mean(Length_cm), stdev=sd(Length_cm))