[英]Divide each element in each row of a dataframe by the value in one of the rows in R
我想通过一个特定列中的值来标准化 dataframe。 换句话说,我想将每一行中的所有值除以特定列中的值。
例如:
dataframe 是
Gene P1 P2 P3
A1 6 8 2
A2 12 6 3
A3 8 4 8
我想将每行中的所有值除以 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
新的 dataframe 将是:
Gene P1 P2 P3
A1 3 4 1
A2 4 2 1
A3 1 .5 1
谢谢您的帮助。
您可以直接划分列 -
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
使用 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.