R语言使用dplyr按指定AOI分类汇总时长并计算占比
实现方案
核心逻辑是在分组汇总前,先对AOI字段做重编码,将所有A/B/C的取值统一替换为X,再按新的AOI分组计算即可,完整可运行代码如下:
library(tidyverse) # 构造示例数据集 d <- structure(list(Line = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L), Speaker = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B"), Utterance = c("hi there", "hi there", "hi there", "hi there", "hi there", "how're ya", "how're ya", "how're ya", "how're ya", "how're ya", "how're ya"), Gaze_by = c("A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B"), AOI = c("C", "*", "B", "*", "C", "*", "A", "*", "A", "*", "C"), dur = c(100L, 25L, 30L, 50L, 144L, 50L, 22L, 33L, 100L, 150L, 999L)), row.names = c(NA, -11L), class = c("tbl_df", "tbl", "data.frame")) # 数据处理代码 d %>% # 重编码AOI列:取值为*的保留原值,其余A/B/C统一替换为X mutate(AOI = if_else(AOI == "*", "*", "X")) %>% # 按指定字段分组 group_by(Speaker, Utterance, Gaze_by, AOI) %>% summarise(dur = sum(dur), .groups = "drop_last") %>% # 计算各AOI分类的时长占比,保留1位小数 mutate(prop = round(dur/sum(dur)*100, 1))
运行以上代码即可得到你需要的输出结果:
# A tibble: 4 × 6 # Groups: Speaker, Utterance, Gaze_by [2] Speaker Utterance Gaze_by AOI dur prop <chr> <chr> <chr> <chr> <int> <dbl> 1 A hi there A * 75 21.5 2 A hi there A X 274 78.5 3 B how're ya B * 233 17.2 4 B how're ya B X 1121 82.8
内容的提问来源于stack exchange,提问作者Chris Ruehlemann
相关产品推荐
相关产品推荐

