在R中,从列本身和该列的所有行中减去列中的第一行(除一列外的所有列)

在R中,从列本身和该列的所有行中减去列中的第一行(除一列外的所有列),r,dplyr,R,Dplyr,我有一个表格,其中第一列是时间点(例如,0分钟、10分钟等),每一列是不同的测试,每一行在每个时间点都有一个测量值。(对于这里的微生物学家:96孔培养皿中的细菌生长曲线。)我想做一个背景校正,从每一列自身和所有其他列中减去时间0测量值,这样在时间0时,每个测量值都是0。但是,时间列应保持不变 > input time A1 A2 A3 0 1 1 2 10 2 3 3 20 3 5 4 30 4 7 5

我有一个表格,其中第一列是时间点(例如,0分钟、10分钟等),每一列是不同的测试,每一行在每个时间点都有一个测量值。(对于这里的微生物学家:96孔培养皿中的细菌生长曲线。)我想做一个背景校正,从每一列自身和所有其他列中减去时间0测量值,这样在时间0时,每个测量值都是0。但是,时间列应保持不变

> input
time    A1  A2  A3
0       1   1   2
10      2   3   3
20      3   5   4
30      4   7   5

>output
time    A1  A2  A3
0       0   0   0
10      1   2   1
20      2   4   2
30      3   6   3

我试过
df$A1=df$A1-df$A1[1]
,虽然这样做有效,但我有96列,这会变得很乏味。

使用
dplyr
可以:

library(dplyr)
input <- input %>% mutate(across(A1:A3, ~. - .[time == 0]))
input

#  time A1 A2 A3
#1    0  0  0  0
#2   10  1  2  1
#3   20  2  4  2
#4   30  3  6  3
数据

input <- structure(list(time = c(0L, 10L, 20L, 30L), A1 = 1:4, A2 = c(1L, 
3L, 5L, 7L), A3 = 2:5), class = "data.frame", row.names = c(NA, -4L))
input <- structure(list(time = c(0L, 10L, 20L, 30L), A1 = 1:4, A2 = c(1L, 
3L, 5L, 7L), A3 = 2:5), class = "data.frame", row.names = c(NA, -4L))

input使用
dplyr
可以执行以下操作:

library(dplyr)
input <- input %>% mutate(across(A1:A3, ~. - .[time == 0]))
input

#  time A1 A2 A3
#1    0  0  0  0
#2   10  1  2  1
#3   20  2  4  2
#4   30  3  6  3
数据

input <- structure(list(time = c(0L, 10L, 20L, 30L), A1 = 1:4, A2 = c(1L, 
3L, 5L, 7L), A3 = 2:5), class = "data.frame", row.names = c(NA, -4L))
input <- structure(list(time = c(0L, 10L, 20L, 30L), A1 = 1:4, A2 = c(1L, 
3L, 5L, 7L), A3 = 2:5), class = "data.frame", row.names = c(NA, -4L))

input我们可以使用
base R
在进行减法之前使用
col
进行复制,使长度相同

input[-1] <- input[-1] - input[-1][input$time == 0][row(input[-1])]
input[-1]
#  A1 A2 A3
#1  0  0  1
#2  0  1  1
#3  0  2  1
#4  0  3  1

input[-1]我们可以使用
base R
,在进行减法之前,使用
col
进行复制,使长度相同

input[-1] <- input[-1] - input[-1][input$time == 0][row(input[-1])]
input[-1]
#  A1 A2 A3
#1  0  0  1
#2  0  1  1
#3  0  2  1
#4  0  3  1
输入[-1]