当所有值都位于R中数据帧的同一列时,计算百分比

当所有值都位于R中数据帧的同一列时,计算百分比,r,percentage,R,Percentage,我有以下数据框 x <- data.frame("treatment"= c(1, 1, 1, 1, 2, 2, 2, 2), "Time" = c(0, 30, 60, 180, 0, 30, 60, 180), "cells_alive" = c(500, 470, 100, 20, 476, 310, 99, 2)) x使用数据表 library(data.tab

我有以下数据框

x <- data.frame("treatment"= c(1, 1, 1, 1, 2, 2, 2, 2), 
              "Time" = c(0, 30, 60, 180, 0, 30, 60, 180), 
              "cells_alive" = c(500, 470, 100, 20, 476, 310, 99, 2))

x使用
数据表

library(data.table)
setDT(x) #converting x to data.table 
x[,.(Time, value = cells_alive / cells_alive[which(Time == 0)]),treatment]

#output
   treatment Time       value
1:         1    0 1.000000000
2:         1   30 0.940000000
3:         1   60 0.200000000
4:         1  180 0.040000000
5:         2    0 1.000000000
6:         2   30 0.651260504
7:         2   60 0.207983193
8:         2  180 0.004201681

发布
dplyr
data.table
版本后,为了完整起见,这里有一个不需要安装软件包的版本:

stack(tapply(x$cells_alive, x$treatment, function(ca) ca / ca[1] ))

> stack(tapply(x$cells_alive, x$treatment, function(ca) ca / ca[1] ))
       values ind
1 1.000000000   1
2 0.940000000   1
3 0.200000000   1
4 0.040000000   1
5 1.000000000   2
6 0.651260504   2
7 0.207983193   2
8 0.004201681   2

谢谢,效果很好!现在,如果我在治疗中也有复制,它会如何工作?
> stack(tapply(x$cells_alive, x$treatment, function(ca) ca / ca[1] ))
       values ind
1 1.000000000   1
2 0.940000000   1
3 0.200000000   1
4 0.040000000   1
5 1.000000000   2
6 0.651260504   2
7 0.207983193   2
8 0.004201681   2