在一个数据帧(请参见下文)中,我想计算每个活动/事件的频率(请参见第二列)。事件的频率应显示在适当的列中(第三至第六)。
例如在第3列(打开文档)和第2行(用户1)中应将数字写为“ 1”,在第6列(关闭文档)中也应将数字写为“ 1”。
或者如果用户4编辑文档五次,则应在第5列(“编辑文档”)和第5行(用户4)中显示“ 5”。
由于大量的用户,还需要循环功能。
user activity Open Document Read Document Edit Document Close Document
1 c("Open Document", "Close Document", …)
2 c("Open Document", "Read Document", …)
3 c("Open Document", "Close Document", …)
4 c("Open Document", "Edit Document", …)
感谢您的帮助。
答案 0 :(得分:3)
您可以使用table
计算事件发生的次数。我使用strsplit
拆分为单个活动,并使用所有活动的级别制作一个factor
:
x[,-1:-2] <- do.call(rbind, lapply(strsplit(x$activity, ",")
, function(i) table(factor(i, levels=colnames(x)[-1:-2]))))
x
# user activity Open Read Edit Close
#1 1 Open,Close 1 0 0 1
#2 2 Open,Read 1 1 0 0
#3 3 Open,Close 1 0 0 1
#4 4 Open,Edit 1 0 1 0
数据:
x <- data.frame(user=1:4, activity=c("Open,Close", "Open,Read", "Open,Close", "Open,Edit")
, Open=0, Read=0, Edit=0, Close=0, stringsAsFactors=FALSE)