Calculate relationship between columns based on condition in R

Hi, I am doing a very simple job 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 greater than 5.

The code I use 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 could not use the condition. I know it is trivial, but it takes a lot of time. I appreciate your help.

+5
source share
4 answers

You can use ifelse. You are not saying that you want the result to be when b is less than 5, so I assumed that you want NAthere:

> 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
+5
source

I think it transformis more elegant here :) (slightly different from @Ananda's solution)

 transform(df, d= ifelse(b > 5, b/c, NA))
  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
+4

df$d with().

df$d[df$b>5] <- with(df[df$b>5,],b/c)
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
+3

First, I calculated the coefficient, and then assigned the NAvalues, where b < 5:

df = within(df, { d = b / c })
df$d[df$b <= 5] <- 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
+1
source

All Articles