Home > Software engineering >  Replacing certain NA values with a specific value
Replacing certain NA values with a specific value

Time:08-31

I am trying to edit NAs in my data for visualization purposes. I would like to replace some of the NAs with the value "31". However, I only want the NAs replaced in the column "Cq" only where "Dilution" = 1 or 1:1. Here is an example of my data frame:

Sample Dilution Cq
1 1 NA
1 1:1 NA
1 1:5 27
2 1 13
2 1:1 14
2 1:5 15

I've been trying mutate_if and na_replace but I lack knowledge about the syntax to do this appropriately.

CodePudding user response:

We can use ifelse (or case_when) with your conditions:

your_data %>%
  mutate(Cq = ifelse(is.na(Cq) & Dilution %in% c("1", "1:1"), 31, Cq))
#   Sample Dilution Cq
# 1      1        1 31
# 2      1      1:1 31
# 3      1      1:5 27
# 4      2        1 13
# 5      2      1:1 14
# 6      2      1:5 15

Using this data:

your_data = read.table(text = 'Sample   Dilution    Cq
1   1   NA
1   1:1     NA
1   1:5     27
2   1   13
2   1:1     14
2   1:5     15', header = T)

CodePudding user response:

Using the data.table package, I've written some code below illustrating how you would be able to replace the NA values of Cq only when Dilution is 1 or 1:1.

library(data.table)

data <- data.table(
  Sample = c("1","1","1","2","2","2"),
  Dilution = c("1","1:1","1:5","1","1:1","1:5"),
  Cq = c(NA_real_, NA_real_, 27, 13, 14, 15))

data
Sample Dilution Cq
1:      1        1 NA
2:      1      1:1 NA
3:      1      1:5 27
4:      2        1 13
5:      2      1:1 14
6:      2      1:5 15

data[Dilution %in% c("1","1:1") & is.na(Cq)] <- 31

data
   Sample Dilution Cq
1:     31       31 31
2:     31       31 31
3:      1      1:5 27
4:      2        1 13
5:      2      1:1 14
6:      2      1:5 15
  • Related