Leandro Jimenez
Leandro Jimenez

Reputation: 99

apply function with a conditional statement using two dataframe

I have two data frame x and y.

x<-data.frame("j"=c("A","B","C"),"k"=c(1,90,14))
  x j  k
  1 A  1
  2 B 90
  3 C 14

y<-data.frame("A"=c(1,0,0,1,1),"B"=c(0,1,0,0,1),"C"=c(1,1,1,0,0))
  A B C
1 1 0 1
2 0 1 1
3 0 0 1
4 1 0 0
5 1 1 0

I need a function with a conditional statement where if in the data set y there is a 0 a replace by -1 or 1 replace by 1 in the column A and so on to get this result.

z<-data.frame("A"=c(1,-1,-1,1,1),"B"=c(-90,90,-90,-90,90),"C"=c(14,14,14,-14,-14))
   A   B   C
1  1 -90  14
2 -1  90  14
3 -1 -90  14
4  1 -90 -14
5  1  90 -14

Upvotes: 0

Views: 253

Answers (1)

lmo
lmo

Reputation: 38500

Here is a fun one-liner in base R that uses a number of good-to-know functions.

setNames(do.call(data.frame, Map(function(x, y) x * c(-1, 1)[y+1], x$k, y)), LETTERS[1:3])
   A   B   C
1  1 -90  14
2 -1  90  14
3 -1 -90  14
4  1 -90 -14
5  1  90 -14

The inner most function x * c(-1, 1)[y+1] takes the value of x (which is a scalar -- either 1, 90, or 14) and multiplies it by either negative -1 or 1 depending on the value of y.

Map takes the values of x$k for x and the variables of the data.frame y for the y argument, performs the function on each pair and returns a list. with three vectors.

This list is converted to a data.frame with do.call and the names of the variables are supplied with setNames.

Upvotes: 1

Related Questions