GK89
GK89

Reputation: 664

Complicated R Function for picking max Values

I have a data frame...

a <- c(6,9,12,13,15,20)
b <- c(1,12,36,2,48,3)
c <- c(50,0,2,35,12,60)
df = data.frame(a,b,c)
#   a  b  c
#1  6  1 50
#2  9 12  0
#3 12 36  2
#4 13  2 35
#5 15 48 12
#6 20  3 60

What I would like to do is

if there is no higher number, the function simply terminates and only reports the last number that was higher

The output is a data frame where each column is the combination

Is this possible to do in R as a function?

The output can be can be a data frame of the following format

c1 <- c(6,12,50)
c2 <- c(6,36,50)
c3 <- c(6,48,50)
c4 <- c(9,12,50)
c5 <- c(9,36,50)
c6 <- c(9,48,50)
c7 <- c(12,36,50)
c8 <- c(12,48,50)
c9 <- c(13,36,50)
c10 <- c(13,48,50)
c11 <- c(15,36,50)
c12 <- c(15,48,50)
c13 <- c(20,36,50)
c14 <- c(20,48,50)
etc
df1 <- data.frame(c1, c2, c3, c4, etc)
#  c1 c2 c3 c4 ...
#1  6  6  6  9 ...
#2 12 36 48 12 ...
#3 50 50 50 50 ...

Upvotes: 0

Views: 69

Answers (1)

akrun
akrun

Reputation: 887118

This gives you all the combinations where the numbers are increasing from first column to last column

 df1 <- do.call(`expand.grid`,lapply(df, unique))
 df2 <- df1[Reduce(`&`,lapply(1:(ncol(df1)-1),
                function(i) df1[,i+1]>df1[,i])),]

 head(df2)
 #    a  b  c
 #7   6 12 50
 #8   9 12 50
 #13  6 36 50
 #14  9 36 50
 #15 12 36 50
 #16 13 36 50

 dim(df2)
 #[1] 30  3

Upvotes: 2

Related Questions