简体   繁体   中英

Replacing NAs with zeros only in non-empty groups

I have a problem that should be easy to solve but I simply cannot figure it out. I have a huge dataset with groups and a variable. Some groups are empty for this variable (filled only with NAs) and some contains values but also NAs.

For example:

ID <- c("A1","A1","A1","A1","B1","B1","B1","B1", "B1", "C1", "C1", "C1")
Value1 <- c(0,2,1,1,NA,1,1,NA,1,NA,NA,NA)
data <- data.frame(ID, Value1)

I would like to change all NAs to zeros but only in groups that otherwise contain information.

So like this:

ID <- c("A1","A1","A1","A1","B1","B1","B1","B1","B1","C1","C1","C1")
Value1 <- c(0,2,1,1,0,1,1,0,1,NA,NA,NA)

I tried to use group_by(ID) and "replace" with the condition max(Value1)>=0 but either max() doesn't work as a condition or it doesn't work with NAs. Unfortunately I would need this kind of conditioning often in my work so I would also appreciate any suggestions on which are the best packages to treat groups selectively.

You can use a simple if` statement, ie

library(dplyr)
library(tidyr)

data %>% 
 group_by(ID) %>% 
 mutate(Value1 = if (all(is.na(Value1))){Value1}else{replace_na(Value1, 0)})

which gives,

 # A tibble: 12 x 2 # Groups: ID [3] ID Value1 <fct> <dbl> 1 A1 0 2 A1 2 3 A1 1 4 A1 1 5 B1 0 6 B1 1 7 B1 1 8 B1 0 9 B1 1 10 C1 NA 11 C1 NA 12 C1 NA

Here is a base R solution

dfout <- Reduce(rbind,
                lapply(split(data,data$ID),
                       function(v) {if (!all(is.na(v$Value1))) v$Value1[is.na(v$Value1)]<- 0; v}))

such that

> dfout
   ID Value1
1  A1      0
2  A1      2
3  A1      1
4  A1      1
5  B1      0
6  B1      1
7  B1      1
8  B1      0
9  B1      1
10 C1     NA
11 C1     NA
12 C1     NA

With dplyr :

data %>%
  group_by(ID) %>%
  mutate(Value1 = ifelse(any(!is.na(Value1)) & is.na(Value1), 0, Value1))

# A tibble: 12 x 2
# Groups:   ID [3]
   ID    Value1
   <fct>  <dbl>
 1 A1         0
 2 A1         2
 3 A1         1
 4 A1         1
 5 B1         0
 6 B1         1
 7 B1         1
 8 B1         0
 9 B1         1
10 C1        NA
11 C1        NA
12 C1        NA

Using data.table

setDT(data)
data[, Value1 := if (all(is.na(Value1))) NA else replace(Value1, is.na(Value1), 0), by = ID]

    ID Value1
 1: A1      0
 2: A1      2
 3: A1      1
 4: A1      1
 5: B1      0
 6: B1      1
 7: B1      1
 8: B1      0
 9: B1      1
10: C1     NA
11: C1     NA
12: C1     NA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM