我对数据框操作有疑问。
我有一个看起来像这样的数据框:
year | month | deviceCategoy | sessions
2017 | 4 | desktop | 140000
2017 | 4 | mobile | 200000
2017 | 4 | tablet | 80000
... ... ... ...
总而言之,数据框包含截至2017年全年的数据。
现在,我想有一个新的数据框,其中只有台式机和移动设备类别。平板电脑的 session 应添加到桌面。
结果应如下所示:
year | month | deviceCategoy | sessions
2017 | 4 | desktop | 220000
2017 | 4 | mobile | 200000
有人知道该怎么做吗?
最佳答案
我们可以将“tablet”字符串更改为“desktop”,然后执行aggregate
i1 <- df1$deviceCategoy == "tablet"
df1$deviceCategoy[i1] <- "desktop"
aggregate(sessions ~ ., df1, sum)
# year month deviceCategoy sessions
#1 2017 4 desktop 220000
#2 2017 4 mobile 200000
或使用
tidyverse
library(dplyr)
df1 %>%
mutate(deviceCategoy = replace(deviceCategoy, deviceCategoy == "tablet", "desktop")) %>%
group_by_at(names(.)[1:3]) %>%
summarise(sessions = sum(sessions))
关于r - 新数据框的总和基于另一个数据框的条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49976770/