0

I have a df with 6 colums. For each row I need to find the min() number, and dependent on which columns it originates from, I need to multiply the number with a number from another df. I have...

  • df1, 44 rows, 6 columns
  • df2, 44 rows, 3 columns

if the number originates from df1, colums 1 and 4, it needs to be multiplied with df2[same row, col 1]. Other examples:

  • 2 and 5 with col 2, and
  • 3 and 6 with col 3..
Frank
  • 66,179
  • 8
  • 96
  • 180
  • 1
    please see: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example and update your question as appropriate – B Williams Sep 19 '17 at 21:58

1 Answers1

0

B Williams is right; when asking a question here you really ought to include a reproducible example. It's how you help others help you. I happened to find your description understandable, so I have a solution below, but for future reference a reproducible example is the most reliable way to get help.

The function that you need is which.min():

set.seed(42) # Set the seed for reproducibility
# Then make randomly generated data frames matching your description
df1 <- as.data.frame(matrix(rnorm(44*6), nrow=44, ncol=6))
df2 <- as.data.frame(matrix(rnorm(44*3), nrow=44, ncol=3))
cols <- rep(1:3, 2) # This helps index columns of df2
products <- sapply(1:44, function(i){ # for every row
    ind <- which.min(df1[i, ]) # find the column with the min value
    return(df1[i, ind] * df2[i, cols[ind]]) # and return the relevant product
})

To see that this worked, we can check the answer for the first row:

df1[1, ]
        V1        V2        V3           V4        V5        V6
1 1.370958 -1.368281 0.9333463 6.288407e-05 -1.449007 0.3856679

which.min(df1[1, ])
V5 
 5 

df1[1, 5]
[1] -1.449007

df2[1, 2]
[1] -1.246395

df1[1, 5] * df2[1, 2]
[1] 1.806036

products[1]
[1] 1.806036
duckmayr
  • 16,303
  • 3
  • 35
  • 53