Add the NA per group in r (without the apply, lapply, etc functions)

0

I try to add the NA per group and create a data.frame of the group and the number of NAs.

Example: from the following set:

Group Value
A        4
A        4
B        NA
B        4

I need to get:

Group #NA
A      0
B      1
    
asked by David Alejandro 30.09.2016 в 22:04
source

2 answers

1

Dear. I have managed to solve the problem thanks to some friends, I share the solution:

data<-data.frame(Group=c("A","A","B","B"),Value=c(4,4,NA,4))  

with(data,aggregate(Value,list(Group),function(x){sum(is.na(x))}))

 Group.1 x  
1       A 0  
2       B 1
    
answered by 04.10.2016 в 21:32
0

Another solution with dplyr:

library(dplyr)

data <- data.frame(Group=c("A","A","B","B"), 
                   Value=c(4,4,NA,4))

data %>%
  mutate(nas = ifelse(is.na(Value), 1, 0)) %>% 
  group_by(Group) %>% 
  summarize(sum(nas))
    
answered by 07.10.2016 в 05:20