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

Calculate percentage when all values are in the same column of a dataframe in R

我有以下数据框

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))

在这个实验中,我有两种处理方法,我测量了随时间变化的活细胞数量。时间 0 的细胞数是该处理的初始细胞数。我需要计算新列中每次存活的细胞百分比。因此,在治疗 1 的情况下,它将是 500/500、470/500、100/500 等等。关于如何计算这个的任何想法?

谢谢

require(tidyverse)

x %>% 
left_join(x %>% select(treatment, cells_alive) %>% 
group_by(treatment) %>% 
top_n(1) %>% 
ungroup(), by = "treatment") %>% 
mutate(cells_alive_per = cells_alive.x/cells_alive.y)

使用data.table

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

发布dplyrdata.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