R 根据组和条件划分两行值
我想将第4列(“计数”)中的值除以2行,其中第一列的值相同 我尝试使用“group_by”,但无法告诉R我想用快速计数值除以慢速计数值。换句话说,我不知道如何单独访问这些值R 根据组和条件划分两行值,r,R,我想将第4列(“计数”)中的值除以2行,其中第一列的值相同 我尝试使用“group_by”,但无法告诉R我想用快速计数值除以慢速计数值。换句话说,我不知道如何单独访问这些值 cells一种涉及dplyr的可能性是: df %>% group_by(cells, temps) %>% summarise(div_result = first(counts)/last(counts)) cells temps div_result <fct> <dbl&g
cells一种涉及dplyr的可能性是:
df %>%
group_by(cells, temps) %>%
summarise(div_result = first(counts)/last(counts))
cells temps div_result
<fct> <dbl> <dbl>
1 CELL1 10 1.33
2 CELL1 20 0.417
3 CELL1 30 2.01
4 CELL1 40 4.76
5 CELL2 10 3
6 CELL2 20 3.12
7 CELL2 30 3.33
8 CELL2 40 3.33
df%>%
分组依据(单元格、临时值)%>%
总结(div_结果=第一次(计数)/最后一次(计数))
单元格临时div_结果
1单元1101.33
2单元1200.417
3单元1302.01
4单元1404.76
5单元2103
6单元2 20 3.12
7单元2303.33
8单元2403.33
这里有一种使用dplyr的方法-
df %>%
group_by(cells, temps) %>%
summarize(
div_result = counts[corners == "FAST"]/counts[corners == "SLOW"]
) %>%
ungroup()
# A tibble: 8 x 3
cells temps div_result
<fct> <dbl> <dbl>
1 CELL1 10 1.33
2 CELL1 20 0.417
3 CELL1 30 2.01
4 CELL1 40 4.76
5 CELL2 10 3
6 CELL2 20 3.12
7 CELL2 30 3.33
8 CELL2 40 3.33
df%>%
分组依据(单元格、临时值)%>%
总结(
div_result=计数[角点==“快”]/计数[角点==“慢”]
) %>%
解组()
#一个tibble:8x3
单元格临时div_结果
1单元1101.33
2单元1200.417
3单元1302.01
4单元1404.76
5单元2103
6单元2 20 3.12
7单元2303.33
8单元2403.33
带有基本R的选项
by(df[['counts']], df[c('cells', 'temps')], FUN = function(x) x[1]/x[2])
或使用数据。表格
library(data.table)
setDT(df)[, .(div_results = first(counts)/last(counts)), .(cells, temps)]
aggregate(counts~cells+temp,df,FUN=function(x)x[1]/x[2])
(不过您需要对结果重新排序)
by(df[['counts']], df[c('cells', 'temps')], FUN = function(x) x[1]/x[2])
library(data.table)
setDT(df)[, .(div_results = first(counts)/last(counts)), .(cells, temps)]