简体   繁体   中英

Divide each element in each row of a dataframe by the value in one of the rows in R

I would like to standardize a dataframe by the value in one specific column. In other words, I would like to divide all the values in each row by the value in a specific column.

For example:

The dataframe is

Gene   P1  P2  P3   
A1      6   8   2   
A2      12  6   3   
A3      8   4   8 

I would like to divide all the values in each row by the value in that row for column P3.

Gene   P1     P2    P3   
A1      6/2   8/2   2/2   
A2      12/3  6/3   3/3   
A3      8/8   4/8   8/8 

The new dataframe would be:

Gene   P1  P2  P3       
A1      3   4   1   
A2      4   2   1  
A3      1   .5  1

Thank you for your help.

You can directly divide the columns -

cols <- 2:3
df[cols] <- df[cols]/df$P3
df

#  Gene P1  P2 P3
#1   A1  3 4.0  2
#2   A2  4 2.0  3
#3   A3  1 0.5  8

Using tidyverse functions:

library(tidyverse)
df1 <- read.table(text = "Gene P1 P2 P3
A1 6 8 2
A2 12 6 3
A3 8 4 8", header = TRUE)

df1 %>% 
  mutate(across(.cols = -c(Gene), .fns = ~ .x / P3))
# Gene P1  P2 P3
#1   A1  3 4.0  1
#2   A2  4 2.0  1
#3   A3  1 0.5  1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM