-2
Code:
f<-data %>%
  count(city_name, gender_full== "Male", sort = TRUE)  %>%
  slice_head(n = 10)
colnames(f)=c("city", "Number of male")
f
Output  :
     city          Number of male   NA
1        Vancouver          FALSE 5878
2        Vancouver           TRUE 5333
3         Victoria          FALSE 2572
4         Victoria           TRUE 2313
5          Nanaimo           TRUE 2006
6          Nanaimo          FALSE 1870
7  New Westminster          FALSE 1730
8  New Westminster           TRUE 1481
9          Kelowna          FALSE 1345
10         Kelowna           TRUE 1168

In my output, at the column "Number of male" it has a mixture of "TRUE" and "FALSE". How can i change False to "Female" and True to "Male"?

  • you can use `dplyr::filter(column)`, insert the column with the true/false as the argument instead of `column`. In the data I cannot see the column name. – harre Aug 01 '22 at 16:43
  • 3
    Does this answer your question? [Filter data.frame rows by a logical condition](https://stackoverflow.com/questions/1686569/filter-data-frame-rows-by-a-logical-condition) – user438383 Aug 01 '22 at 16:52

1 Answers1

0

Are you trying to count how many males and how many females are in each city? In your data, is each row a person with a gender and city? If so, can use the classic group_by, summarize combo.

I created this dummy data:

data <- data.frame(ID = c(4,5,6,7,8),
                   city_name = c("Vancouver", "Boston", "Quebec", "Boston", "Boston"),
                   gender_full = c("Male", "Male", "Female", "Male", "Female"))

  ID city_name gender_full
1  4 Vancouver        Male
2  5    Boston        Male
3  6    Quebec      Female
4  7    Boston        Male
5  8    Boston      Female

Group_by and summarize:

library(tidyverse)

data %>%
  group_by(city_name, gender_full) %>% 
  summarise(number = n())

# A tibble: 4 x 3
# Groups:   city_name [3]
  city_name gender_full number
  <chr>     <chr>        <int>
1 Boston    Female           1
2 Boston    Male             2
3 Quebec    Female           1
4 Vancouver Male             1
Maggie
  • 53
  • 5