Split data frame by the first line itself

Asked

Viewed 89 times

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 do the division 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 by 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

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 will be working with a data frame with many columns soon.

1 answer

5


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

  • With the tidyverse.
  • Only on R basis.

In both I will 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 R base.

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 check.

identical(DF2, DF3)
#[1] TRUE

Browser other questions tagged

You are not signed in. Login or sign up in order to post.