gpt4 book ai didi

R:使用 dplyr 计算 B 跟随 A 的次数

转载 作者:行者123 更新时间:2023-12-05 08:46:13 25 4
gpt4 key购买 nike

我有一个 data.frame,其中包含几个月内测得的氡的月平均值。我已将每个值标记为“低于”或“高于”阈值,并想计算平均值出现的次数:“低于至高于”、“高于至低于”、“高于至高于”或“低于至”下”。

df <- data.frame(value = c(130, 200, 240, 230, 130),
level = c("below", "above","above","above", "below"))

在这里深入研究 Matlab 答案表明我们可以使用 Matrix 包:

require(Matrix)
sparseMatrix(i=c(2,2,2,1), j=c(2,2,2))

产生这个我还不能解释的结果。

[1,] | |
[2,] | .

对 tidyverse 方法有什么想法吗?

最佳答案

当然,只需使用 group by 并计算值

library(dplyr)

df <- data.frame(value = c(130, 200, 240, 230, 130),
level = c("below", "above","above","above", "below"))
df %>%
group_by(grp = paste(level, lead(level))) %>%
summarise(n = n()) %>%
# drop the observation that does not have a "next" value
filter(!grepl(pattern = "NA", x = grp))
#> # A tibble: 3 × 2
#> grp n
#> <chr> <int>
#> 1 above above 2
#> 2 above below 1
#> 3 below above 1

关于R:使用 dplyr 计算 B 跟随 A 的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70147939/

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