1

How can I divide positive values of data frame row by a specific column and negative values of same data frame row, by another specific column?

This is the data frame head.

Ex: I need that all values of the first row to be divided by "Assets"column as they are all positive.

On the second row, all values need to be dividided by "Assets" column, but the value associated to the column "RoW", because it is the only negative value of the row.

Any suggestions?

  • 2
    Please see [How to create a great reproducible example in R](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and update your question – Mako212 Feb 13 '19 at 17:02

1 Answers1

0

Suppose the dataframe is df. Then the following should do what you want:

apply(df, FUN=function(x) ifelse(x > 0, x / df$Assets, x / df$Whatever), MARGIN=2)

It iterates over all the columns (MARGIN=2 in apply) and applies the given function to all columns. In each column, positive entries are divided by the corresponding value in the Assets column, non-positive values are divided by the corresponding value in the Whatever column.

Example:

> df <- data.frame(Profit=c(1000,-1000,2000,-2000),
                 Assets=c(1,2,3,4), Whatever=c(-10,-20,-30,-40))

> df

   Profit Assets Whatever
 1   1000      1      -10
 2  -1000      2      -20
 3   2000      3      -30
 4  -2000      4      -40

> apply(df, FUN=function(x) ifelse (x > 0, x / df$Assets,
    x / df$Whatever), MARGIN=2)

         Profit Assets Whatever
 [1,] 1000.0000      1        1
 [2,]   50.0000      1        1
 [3,]  666.6667      1        1
 [4,]   50.0000      1        1
JohnB
  • 13,315
  • 4
  • 38
  • 65