[英]How can I perform different operations in the same column of data frame?
I'm using R to analyze data.我正在使用 R 来分析数据。 I have an ordered grouped time series that shows the brightness of a sample at different times, starting at 0我有一个有序的分组时间序列,显示样本在不同时间的亮度,从 0 开始
Group团体 | Time时间 | Brightness亮度 | Retention保留 |
---|---|---|---|
A一种 | 0 0 | 100 100 | NA北美 |
A一种 | 50 50 | 70 70 | = 70 /100 = 70 /100 |
A一种 | 100 100 | 20 20 | = 20/100 = 20/100 |
B乙 | 0 0 | 90 90后 | NA北美 |
B乙 | 50 50 | 80 80 | = 80 /90 = 80 /90 |
B乙 | 100 100 | 50 50 | = 50/90 = 50/90 |
To calculate retention, I have to divide by the brightness at time 0 for that group.要计算保留时间,我必须除以该组在时间 0 时的亮度。 But there are multiple time zeros throughout the table.但是整个表中有多个时间零点。 I tried using a for loop, but due to the length of the data, this takes about 15 seconds to run;我尝试使用 for 循环,但由于数据的长度,这需要大约 15 秒才能运行; I'm looking for more efficient ways.我正在寻找更有效的方法。
Thanks for helping:)感谢您的帮助:)
You can use ifelse
to calculate Retention
on Time
not equal to 0.您可以使用ifelse
来计算Retention
on Time
不等于 0。
library(dplyr)
df %>%
group_by(Group) %>%
mutate(Retention = ifelse(Time != 0, Brightness/Brightness[Time == 0], NA))
# A tibble: 6 × 4
# Groups: Group [2]
Group Time Brightness Retention
<chr> <int> <int> <dbl>
1 A 0 100 NA
2 A 50 70 0.7
3 A 100 20 0.2
4 B 0 90 NA
5 B 50 80 0.889
6 B 100 50 0.556
df <- structure(list(Group = c("A", "A", "A", "B", "B", "B"), Time = c(0L,
50L, 100L, 0L, 50L, 100L), Brightness = c(100L, 70L, 20L, 90L,
80L, 50L)), class = "data.frame", row.names = c(NA, -6L))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.