【发布时间】:2014-10-12 23:03:27
【问题描述】:
我是 r 的新手,我必须计算以“:”分隔的列中的值。
数据集中有 4 个类别,我必须计算每个类别的操作数。每个 log_id 代表一个类别中的唯一操作。如果一个 log_id 有 2 个或多个类别,则意味着该特定操作将计入所有提及的类别。
数据是这样的
user_id log_id categories
001 1334 Perform:Sport_Well:Com.Tent
001 1323 Com.Tent
001 1212 Active
002 1113 NA
002 1478 Com.Tent:Active
002 1134 Sport_Well:Perform
002 1256 Perform
002 1590 Perform
002 1345 NA
002 1478 Com.Tent
002 1134 Sport_Well:Perform
002 1256 Perform
003 1590 Perform
003 1345 Active:Perform
003 1190 Perform:Com.Tent
003 1239 Active:Perform
这是dput:
dat <- structure(list(user_id = c("001", "001", "001", "002", "002",
"002", "002", "002", "002", "002", "002", "002", "003", "003",
"003", "003"), log_id = c("1334", "1323", "1212", "1113", "1478",
"1134", "1256", "1590", "1345", "1478", "1134", "1256", "1590",
"1345", "1190", "1239"), categories = c("Perform:Sport_Well:Com.Tent",
"Com.Tent", "Active", NA, "Com.Tent:Active", "Sport_Well:Perform",
"Perform", "Perform", NA, "Com.Tent", "Sport_Well:Perform", "Perform",
"Perform", "Active:Perform", "Perform:Com.Tent", "Active:Perform")),
.Names = c("user_id", "log_id", "categories"), class = "data.frame", row.names = c(NA, -16L))
所需的输出如下:
user_id category NumActions
001 Perform 1
001 Sport_Well 1
001 Com.Tent 2
001 Active 1
002 Com.Tent 2
002 Active 1
002 Perform 5
002 Sport_Well 2
003 Com.Tent 2
003 Active 2
003 Perform 4
我正在尝试拆分类别,但不知道如何计算具有多个类别的 log_id。
df$cate = str_split(string = df$Ch_Category, pattern = ":")
【问题讨论】:
标签: r