Hi I am doing a very simple thing here.
I have 3 columns of data; a, b and c. I want to calculate the ratio of b and c when the value of b is only greater than 5.
The code I used is as follows:
a <- c(1,2,3,4,5,6,7,8)
b <- c(2,4,5,8,10,12,15,18)
c <- c (10,9,8,15,31,12,13,12)
df <- data.frame(a,b,c)
## Calculate the ratio
df$d <- with(df,b/c)
I calculated the ratio but couldn't use the condition there. I know its trivial but this is taking a lot of time. I appreciate your help.
You can use ifelse
. You don't say what you want the result to be in cases where b is less than 5, so I've assumed you want NA
there.:
> df$d <- with(df, ifelse(b > 5, b/c, NA))
> df
a b c d
1 1 2 10 NA
2 2 4 9 NA
3 3 5 8 NA
4 4 8 15 0.5333333
5 5 10 31 0.3225806
6 6 12 12 1.0000000
7 7 15 13 1.1538462
8 8 18 12 1.5000000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With