user4773130
user4773130

Reputation:

'if' statement in R

Consider the following data:

library(Benchmarking)
x <- c(4,2,4,6,9,2)
y <- c(2,1,5,2,10,4)
k <- c(25,25,25,30,30,30)
d <- data.frame(x,y,k)

Now I want to do the following calculation:

e1 <- dea(d$x, d$y, XREF = d$x, YREF = d$y)

But I want to change it, so XREF and YREF only consider column x in d if k = 25. Something like:

e1 <- dea(d$x, d$y, XREF = d$x if k = 25, YREF = d$y if k = 25)

But this does not work. Can someone show me how to code this in R?

Upvotes: 0

Views: 78

Answers (2)

Axeman
Axeman

Reputation: 35392

with(subset(d, k == 25), dea(d$x, d$y, XREF = x, YREF = y))

Where d$ notation uses the original full data, and direct x and y refers to the variables from the subset.

Upvotes: 1

sebpardo
sebpardo

Reputation: 707

If I interpret your question correctly, you could use apply to easily do this.

If you want XREF and YREF to only consider column x when k = 25, then:

apply(d, 1, function (df) if (df["k"] == 25) {
  dea(df["x"], df["y"], XREF = df["x"], YREF = df["x"]) 
  } else {
      dea(df["x"], df["y"], XREF = df["x"], YREF = df["y"])
    }
)

This is different to the example code you show. That would be equivalent to:

apply(d, 1, function (df) if (df["k"] == 25) {
  dea(df["x"], df["y"], XREF = df["x"], YREF = df["y"]) 
  } else {
      dea(df["x"], df["y"])
    }
)

Upvotes: 0

Related Questions