简体   繁体   中英

Replace values in dplyr

I've got a dataset with some lower detection limit values (values are not consistent) and I want to replace them with half of the detection value.I tried with following r codes but it doesn't work. Can anyone help with this?

dat %>% mutate(value=sub("<0.02500","0.0125",value))

Site    value
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  0.01
NR  0.01
NR  0.01
NR  0.02
NR  0.01
NR  0.01
NR  0.01
NR  0.01
NR  0.01
NR  <0.05100
NR  <0.05100
NR  <0.05100
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  0.02
NR  0.017
NR  0.031
NR  0.025
NR  0.023
NR  0.024
NR  0.023

Assuming that the value column is character (as in the Note at the end or if not convert them first) remove the < character, convert to numeric and multiply each value by 0.5 or 1.

library(dplyr)

dat %>% 
  mutate(value = as.numeric(sub("<", "", value)) * if_else(grepl("<", value), .5, 1))

or using only base R:

transform(dat, value = as.numeric(sub("<", "", value)) * ifelse(grepl("<", value), .5, 1))

Note

Lines <- "Site    value
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  <0.02500
NR  0.01
NR  0.01
NR  0.01
NR  0.02
NR  0.01
NR  0.01
NR  0.01
NR  0.01
NR  0.01
NR  <0.05100
NR  <0.05100
NR  <0.05100
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  <0.05000
NR  0.02
NR  0.017
NR  0.031
NR  0.025
NR  0.023
NR  0.024
NR  0.023"
dat <- read.table(text = Lines, header = TRUE, as.is = TRUE)

We can use data.table :

library (data.table)

setDT(df1)[, value := ifelse(as.character(value)=="<0.02500", 
                             "0.0125", as.character(value)), ][]
#     Site    value
# 1:    NR   0.0125
# 2:    NR   0.0125
# 3:    NR   0.0125
# 4:    NR   0.0125
# 5:    NR   0.0125
# 6:    NR   0.0125
# 7:    NR     0.01
# ...
# 24:   NR <0.05000
# 25:   NR     0.02
# 26:   NR    0.017
# 27:   NR    0.031
# 28:   NR    0.025
# 29:   NR    0.023
# 30:   NR    0.024
# 31:   NR    0.023
#     Site    value

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