gpt4 book ai didi

R Dataframe - 如何计算到某一点的行数?

转载 作者:行者123 更新时间:2023-12-04 09:06:55 24 4
gpt4 key购买 nike

我目前的数据看起来像这样:

1   Saturday  Evening             16.2  235.84
2 Saturday Evening 23.4 235.29
3 Saturday Evening 29.4 232.79
4 Sunday Evening 24.2 233.89
5 Sunday Evening 24.2 233.66
6 Sunday Evening 24.2 233.38
7 Sunday Evening 24.2 232.99
8 Sunday Evening 25.4 233.21
9 Sunday Evening 26.8 232.37
10 Saturday Night 25.6 231.55
11 Saturday Night 24.4 231.19
12 Saturday Night 24.4 231.63
13 Saturday Night 24.4 231.71
14 Sunday Night 25.2 231.23
15 Sunday Night 25.2 231.23
14 Saturday Night 25.2 231.23
15 Saturday Night 25.2 231.23
15 Sunday Night 25.2 231.23

df = structure(list(V2 = c("Saturday", "Saturday", "Saturday", "Sunday",
"Sunday", "Sunday", "Sunday", "Sunday", "Sunday", "Saturday",
"Saturday", "Saturday", "Saturday", "Sunday", "Sunday", "Saturday",
"Saturday", "Sunday"), V3 = c("Evening", "Evening", "Evening",
"Evening", "Evening", "Evening", "Evening", "Evening", "Evening",
"Night", "Night", "Night", "Night", "Night", "Night", "Night",
"Night", "Night"), V4 = c(16.2, 23.4, 29.4, 24.2, 24.2, 24.2,
24.2, 25.4, 26.8, 25.6, 24.4, 24.4, 24.4, 25.2, 25.2, 25.2, 25.2,
25.2), V5 = c(235.84, 235.29, 232.79, 233.89, 233.66, 233.38,
232.99, 233.21, 232.37, 231.55, 231.19, 231.63, 231.71, 231.23,
231.23, 231.23, 231.23, 231.23)), .Names = c("V2", "V3", "V4",
"V5"), row.names = c(NA, -18L), class = "data.frame")

数据仅包括周六和周日,因此它不是连续的(例如,上周日和下周六/工作日开始之间的数据缺失)。每个周末的数据数量各不相同,因此我需要计算每个星期六星期日集合中有多少观察值。假设数据从周六到周日开始,然后又到下一组周六周日,我如何统计每组数据并将其存储在一个向量中?

编辑:例如,使用上面的数据,我想要的输出将是一个包含以下值的向量:[9, 6, 3]

最佳答案

使用 dplyr 解决方案,其中 V2 是您当前的天数列:

library(dplyr)
df %>%
mutate(x = lag(cumsum((V2 == 'Sunday' & lead(V2) == 'Saturday')), default = 0)) %>%
group_by(x) %>%
summarise(z = n()) %>%
select(z)

这产生

      z
<int>
1 9
2 6
3 3

关于R Dataframe - 如何计算到某一点的行数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com