0

I have an established table in R.

mail ct 1 2 3
1000 10 100 20
2000 200 100 30

I want to create a new table with the same column name and row number but different values based on the following calculation

mail ct 1 2 3
1000 10/1000 100/1000 20/1000
2000 200/2000 100/2000 30/2000

The output should look like this...

mail ct 1 2 3
1000 0.01 0.1 0.02
2000 0.1 0.05 0.015

How can I do it in R?

user3594762
  • 885
  • 1
  • 6
  • 8

2 Answers2

2

Here's an approach using dplyr:

library(dplyr)
df1 %>%
  mutate(across(-mail.ct, ~.x/mail.ct))

#  mail.ct    1    2     3
#1    1000 0.01 0.10 0.020
#2    2000 0.10 0.05 0.015

This means: take df1, change all the columns except mail.ct to have them (".x") divide by that row's mail.ct value.

data

df1 <- data.frame(
  check.names = FALSE,
      mail.ct = c(1000L, 2000L),
          `1` = c(10L, 200L),
          `2` = c(100L, 100L),
          `3` = c(20L, 30L)
)
Jon Spring
  • 55,165
  • 4
  • 35
  • 53
2

You can do -

df[-1] <- df[-1]/df$mail.ct
df

#  mail.ct    1    2     3
#1    1000 0.01 0.10 0.020
#2    2000 0.10 0.05 0.015
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213