0

I would like to apply the ifelse condition to the following data frame according to the schema. I can do it repeatedly, but I have a lot of data.

My code:

d <- data.frame(x_1 = sample(1:100,10),x_2 = sample(1:100,10), y_1 =sample(1:100,10), y_2 =sample(1:100,10), 
                 y_3 =sample(1:100,10), y_4 =sample(1:100,10))
ifelse(d$x_1>d$y_1, 0, d$x_1-d$y_1)
ifelse(d$x_2>d$y_2, 0, d$x_2-d$y_2)
ifelse(d$x_1>d$y_3, 0, d$x_1-d$y_3)
ifelse(d$x_2>d$y_4, 0, d$x_2-d$y_4) # x_1>y_5..., x_2>y_6,...

Edit:

My x_.* are days of the week so I have x_1...x_7. But my y_.* are many. Code should work as follows:

x_1-y_1
x_2-y_2
x_3-y_3
x_4-y_4
x_5-y_5
x_6-y_6
x_7-y_7
x_1-y_8
x_2-y_9
.
.
.

Zizou
  • 503
  • 5
  • 18

1 Answers1

2

If you want to compare every x_.* column with every y_.* column you can use outer.

First find out "x" and "y" columns.

x_col <- grep('x', names(d), value = TRUE)
y_col <- grep('y', names(d), value = TRUE)

We can create an index to subset x_col. The ifelse logic can be simplified to pmin

inds <- seq_along(y_col) %% length(x_col)
inds[inds == 0] <- length(x_col)

We can use mapply to subtract columns.

mapply(function(x, y) pmin(0, x - y), d[inds], d[y_col])
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • I don't want compare every x_.* column with every y_.*, but according to the schema I added in Edit. – Zizou Jun 09 '20 at 10:09