How Do I Mutate Values Differently In Separate Columns

Viewed 59

I am fairly new to R and I feel like this should be pretty straightforward, but I keep getting errors. I have a data table called Master2 that has concentration data for several analytes, taken at different stations. My analytes are my column names. Several ND, or non-detect values exist in each column. I would like to change NDs in my TKN column to 0.05 and NDs in all other columns to 0.005.

I was able to easily change all values in the frame to 0.005 with this code:

Master2 <- Master2 %>% mutate_if(is.character, ~ if_else(. == "ND", "0.005", .))

I have tried a variation of approaches (replace, mutate_at...) to try to change NDs in the TKN column separately prior to running this line of code with no success. Below is a mock up of my data, any help is greatly appreciated!

Master2 <- structure(list(Station = c(C3A,C3A,C3A,MD10,MD10,MD10,C10A), 
Date = c(1/15/2009,1/16/2009,1/17/2009,1/18/2009,1/19/2009,1/20/2009,1/21/2009),
DissAmmonia = c(0.3,0.25,0.18,ND,1.2,0.5,0.8),
DissNitrateNitrite = c(0.6,ND,0.15,0.2,0.4,0.6,ND),
TotPhos = c(0.1,0.3,ND,0.4,0.2,0.12,0.1),
TKN = c(ND,0.2,0.13,0.5,ND,0.8,1.2)))
3 Answers

You can do :

#Change 'ND' values in TKN to 0.05
Master2$TKN[Master2$TKN == 'ND'] <- 0.05
#Change 'ND' values in all other columns to 0.005
Master2[Master2 == 'ND'] <- 0.005
#Change the classes of data to respective types.
Master2 <- type.convert(Master2, as.is = TRUE)
Master2

#  Station          Date DissAmmonia DissNitrateNitrite TotPhos  TKN
#1     C3A 0.00003318401       0.300              0.600   0.100 0.05
#2     C3A 0.00003111000       0.250              0.005   0.300 0.20
#3     C3A 0.00002928000       0.180              0.150   0.005 0.13
#4    MD10 0.00002765334       0.005              0.200   0.400 0.50
#5    MD10 0.00002619790       1.200              0.400   0.200 0.05
#6    MD10 0.00002488800       0.500              0.600   0.120 0.80
#7    C10A 0.00002370286       0.800              0.005   0.100 1.20

If you want to stick with dplyr and still use mutate, try:

Master2 <- Master2 %>%
  mutate(TKN = case_when(TKN == "ND" ~ 0.05, TRUE ~ TKN)) %>%
  mutate(across(select(-TKN), ~case_when(cur_column() == "ND" ~ 0.005,
                                                TRUE ~ cur_column())))

As you haven't provided a reproducible example, I can't test this code to verify I get your desired output

A combination of my code and @Ronak Shah's solution appears to work!

#Change 'ND' values in TKN to 0.05
Master2$TKN[Master2$TKN == 'ND'] <- 0.05
#Change 'ND' values in all other columns to 0.005
 Master2 <- Master2 %>% 
     mutate_if(is.character, ~ if_else(. == "ND", "0.005", .)) 
Related