[英]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.我有一个具有一些较低检测限值的数据集(值不一致),我想用一半的检测值替换它们。我尝试使用以下 r 代码,但它不起作用。 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.假设value
列是字符(如最后的注释中或如果不先转换它们)删除<
字符,转换为数字并将每个值乘以 0.5 或 1。
library(dplyr)
dat %>%
mutate(value = as.numeric(sub("<", "", value)) * if_else(grepl("<", value), .5, 1))
or using only base R:或仅使用基础 R:
transform(dat, value = as.numeric(sub("<", "", value)) * ifelse(grepl("<", value), .5, 1))
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
:我们可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.