I want to use an IF statement to output a gender/sex count if the table contains either gender or sex. I am using R markdown and want it to output a message such as "No gender/sex variable in this dataset" and move to the next block if there is no gender/sex variable in the dataset. If I run my code on a table that contain gender or sex it runs without any problem, but if the table does not contain gender or sex it will throw an error "Missing value where TRUE/FALSE needed", I want my own custom message instead of an error. below is my code:
sex_or_gender <- location %>%
select_if(names(.) %in% "sex" | names(.) %in% "gender")
if(names(location) %in% "sex" || names(location) %in% "gender") {
sex_or_gender %>%
group_by(sex_or_gender[1] %>%
summarise(sex_count = n())
} else{
print("No gender/sex variable in this dataset")
}
Result should be either;
|sex| sex_count|
| M | 256 |
| F | 301 |
| NA| 25 |
or
|gender| sex_count|
| M | 256 |
| F | 301 |
| NA | 25 |
or
No gender/sex variable in this dataset
NOTE: The returned data frame contains only one variable, either sex or date depending on which is used
Aucun commentaire:
Enregistrer un commentaire