Divide data frame by the first line of itself

3

I'm trying to create an index number from a data frame. I would like to divide each column by the first number without having to divide it column by column.

Just as an example, df would be:

DF1 <- data.frame(Name = c("Aaron", "Blake"), Jan = c(2, 5), Feb = c(4, 6), Mar = c(3, 4))

Making column to column, for example:

library(tidyverse)
DF1$Fev/first(DF1$Fev)*100

the result is expected:

[1] 100 150

But doing

DF1[,-1]/first(DF1[,-1])*100

I get

  Jan Fev Mar
1 100 200 150
2 100 120  80

The appropriate would be

   Name Jan Fev      Mar
1 Aaron 100 100 100.0000
2 Blake 250 150 133.3333

Can anyone help me? I'm going to work with a data frame with many columns soon.

    
asked by anonymous 09.11.2018 / 21:59

1 answer

5

There are several ways to do what you want. I'll use two of them.

  • With tidyverse .
  • Only with R base.

In both, I'm going to work with copies of DF1 . First tidyverse .

library(tidyverse)

DF2 <- DF1
DF2[-1] <- DF2[-1] %>%
  mutate_all(funs(./first(.)*100))

DF2
#   Name Jan Feb      Mar
#1 Aaron 100 100 100.0000
#2 Blake 250 150 133.3333

Now base R.

DF3 <- DF1
DF3[-1] <- lapply(DF3[-1], function(x) x/x[1]*100)

DF3
#   Name Jan Feb      Mar
#1 Aaron 100 100 100.0000
#2 Blake 250 150 133.3333

Final verification.

identical(DF2, DF3)
#[1] TRUE
    
09.11.2018 / 23:33