Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform calculations with entries including "<"-operator? In this context, dividing upper limit by two

Tags:

r

I have a data frame of ecological data where some entries are lower than what is in chemistry called LOQ (limit of quantificantion). These measurements are reported as "less than LOQ". What I want to do is to change these values to half of the LOQ. I could probably find code to remove the "<", but then I wouldn't know which of the entries to divide by 2.

#creating df 
x1 <- c(1,2,"<1")
x2 <- c(3,"<4",3)
x3 <- c(1,2,3)
df <- data.frame(x1,x2,x3)
df

x1 x2 x3
1  1  3  1
2  2 <4  2
3 <1  3  3

I want the results to be as:

##### result #######
x1 <- c(1,2,0.5)
x2 <- c(3,2,3)
x3 <- c(1,2,3)
result <- data.frame(x1,x2,x3)

   x1 x2 x3
1 1.0  3  1
2 2.0  2  2
3 0.5  3  3

So that, basically, the < sign is ignored and the remaining values are divided by 2. Any ideas on how to do this?

like image 296
Yung Gud Avatar asked Nov 15 '25 20:11

Yung Gud


1 Answers

Use the fact that a matrix object can be referenced in either 1 or 2 dims.

m <- as.matrix(df) 
isLT <- function(t) substr(t,1,1) == '<' 
islt <- which(isLT(m)) 
delLT <- function(x) substr(x,2,length(x)) 
m[islt] <- delLT(m[islt]) 
mode(m) <- 'numeric'
m[islt] <- m[islt] / 2
like image 103
Norm Matloff Avatar answered Nov 18 '25 10:11

Norm Matloff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!