简体   繁体   English

将 dataframe 的每一行中的每个元素除以 R 中的一行中的值

[英]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.我想通过一个特定列中的值来标准化 dataframe。 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 dataframe 是

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.我想将每行中的所有值除以 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:新的 dataframe 将是:

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:使用 tidyverse 函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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