Home > Blockchain >  Produce new multi-column data frame from existing multi-column data frames with logic
Produce new multi-column data frame from existing multi-column data frames with logic

Time:05-26

I have 3 data frames each with multiple columns. All columns are numeric values, and I would like to produce a fourth with logic like

# this doesn't work when data frames have more than one column
d <- ifelse(A > 0, B, C)

However all the samples of ifelse I've seen produce only a single output column. I'd like to operate on all columns. How can I achieve this?

For example, given these data frames

pivot <- data.frame(a=c(-1, 1), b=c(1, 1))
low <- data.frame(a=c(2.2, 3.3), b=c(4.4, 5.5))
high  <- data.frame(a=c(10.1, 11.2), b=c(12.3, 14.4))

I'd like some expression like

result <- ifelse(pivot > 0, high, low)

to produce

data.frame(a=c(2.2, 11.2), b=c(12.3, 14.4))

CodePudding user response:

Converting to matrix will solve the case

 as.data.frame(ifelse(pivot > 0, as.matrix(high), as.matrix(low)))

-output

    a    b
1  2.2 12.3
2 11.2 14.4
  • Related