Ignore NAs when counting frequency of values

Viewed 64

I am new to R and am trying to count how often a certain value occurs in a variable ('Q1'), and store that number in a new variable ('Freqnt'). I want to ignore NAs.

I have managed to get something to work:

library(dplyr)
test3 <- test3 %>% group_by(Q1) %>% mutate(Freqnt=n())

#     Q1      Freqnt
#1    1       6
#2    1       6
#3    1       6
#4    1       6
#5    1       6
#6    1       6
#7   NA       2
#8   NA       2

As you can see this works but this also counts NAs, which I do not want.

The following does not count the NAs, but it completely removes the rows with NAs, which I don't want either:

test3 <- test3 %>% filter(!is.na(Q1)) %>% group_by(Q1) %>% mutate(Freqnt=n())

#     Q1      Freqnt
#1    1       6
#2    1       6
#3    1       6
#4    1       6
#5    1       6
#6    1       6

How can I, instead of dropping rows with NAs, enter something like 'NA' or leave the cell empty for the Freqnt variable, if Q1 cannot be counted?

Thanks!

1 Answers

We could do

library(dplyr)
test3 %>%
  mutate(Freqnt = Q1) %>%
  group_by(Q1) %>% 
  mutate(Freqnt= if(all(is.na(Q1))) NA_real_ else sum(!is.na(Freqnt))) %>%
  ungroup
Related