简体   繁体   English

如何在同一列数据框中执行不同的操作?

[英]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

Data数据

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.

相关问题 使用应用函数对数据框中的每一列执行不同的操作 - Using apply functions to perform different operations for each column in a data frame 如何按不同的列比较 R 数据帧中的两行并对它们执行操作? - How can I compare two rows in R data frame by different columns and perform an operation on them? 如何根据R数据帧的两列中的位置之间的值执行数学运算? - How do I perform mathematical operations between values in two columns of an R data frame based on their position? 我需要帮助思考如何拆分数据框以执行操作 - I need help thinking about how to split a data frame to perform operations 如何在R数据帧上执行SQL操作? - How can I do SQL like operations on a R data frame? 如何按日期对数据帧进行子集化并在 R 中执行多个操作? - How to subset data frame by date and perform multiple operations in R? 对同一数据框内的不同因素执行相同的线性回归 - Perform same linear regression on different factors within same data frame 如何对共享另一列中给出的相同ID的所有行在数据框中标准化列值? - How can I normalize column values in a data frame for all rows that share the same ID given in another column? 如何在 R 中添加一个列,其值引用不同数据框中的列? - How can I add a column in R whose values reference a column in a different data frame? 将其导出为csv时,如何在R数据框中保持相同的列格式? - How can I maintain the same column format in R data frame when i export it as csv?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM