Within a data frame (see below), I would like to compute the frequency of each activity/event (see second column). The frequency of the events should be shown in the appropriate columns (third until sixth).
Eg in column 3 (Open Document) and row 2 (user 1) should be written the number "1" and in column 6 (Close Document) should also be computed "1".
Or if user 4 edits a document five times, then "5" should be shown in column 5 (Edit Document) and row 5 (user 4).
Also a loop-function is needed due to a massive amount of users.
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", …)
Thanks for your help.
You can use table
to count the frequency of events . I use strsplit
to split to single activities and make a factor
with the levels of all activities:
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
Data:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.