[英]R - Count consecutive occurrences of a specific number based on a specific group
[英]Count number of. consecutive occurrences in sequence per group in R
我有一个轻微的程序问题,我似乎无法弄清楚。 我想知道如何以优雅的方式计算从 r 中每组的不同值开始的序列中连续数字的数量
例如,我们有一个带有名称和数字的数据框,并希望找到最小化数据框,每个名称只保留 1 个条目,另一个是每个名称的连续条目数
names <- c(rep("bob",5), rep("henry",5), rep("maria",5))
goals <- c(1,2,3,5,4, 4,3,4,5,2, 1,2,4,6,5)
input.df <- data.frame(names, goals)
所以从 1 开始,输出数据框会像下面的那样,其中“bob”有一个 3,因为他的目标是从 1 到 3 个连续的目标条目,亨利有 0,因为他没有 1 或任何有序条目和玛丽亚有 2 个因为她有从 1 到 2 的条目
names <- c("bob", "henry", "maria")
runs <- c("3", "0", "2")
output.df.from.1 <- data.frame(names, goals)
从 3 开始,bob 和 maria 都是 0,但 henry 现在是 3,因为他有 3、4、5。
names <- c("bob", "henry", "maria")
runs <- c("0", "3", "0")
output.df.from.3 <- data.frame(names, goals)
我确信必须有一个简单的解决方案,但我找不到任何解决方案,但是我可能正在寻找错误的东西。
有人有建议吗?
这是您的答案的可能解决方案。 思路是1)先找出每个人的(多个)连续数字,然后2)给定一个值,从该值开始找出连续数字的长度。
考虑到每个人可以有多个连续数字的情况,我稍微更改了您的示例数据。 (例如,bob 现在有数字 1、2、3、5、4、7、8、9,连续的组是 1、2、3 和 7、8、9)。
names
,每个组内,发现的以前和未来的数字goals
。 如果它是连续的,那么previous_goal - current_goal = -1
或next_goal - current_goal = 1
。 注意我同时使用上一个/下一个以保留连续组中的所有值。library(tidyverse)
names <- c(rep("bob",8), rep("henry",5), rep("maria",5))
goals <- c(1,2,3,5,4, 7,8,9, 4,3,4,5,2, 1,2,4,6,5)
df1 <- data.frame(names, goals)
df2 <- df1 %>%
group_by(names) %>%
mutate(goals_lag = lag(goals) - goals) %>%
mutate(goals_lead = lead(goals) - goals) %>%
filter(goals_lag == -1 | goals_lead == 1) %>%
select(-goals_lag, -goals_lead)
cons_len <- function(df, name, start_val){
# take goals as a vector
vec <- (df %>% filter(names == name))$goals
# find the starting positions of different groups
vec_stops <- which( (vec - c(vec[1] - 1, vec[-length(vec)])) != 1)
# find the index of the given value
vec_start <- which(vec == start_val)
# if not find the value, return 0
if (length(vec_start)==0) {
return(0)
# if there is only one group of consecutive numbers
} else if (length(vec_stops) == 0) {
return(length(vec) - vec_start + 1)
} else {
# if there are multiple groups of consecutive numbers
len <- vec_stops[vec_start <= vec_stops][1] - vec_start
return(ifelse(len == 1, 0, len))
}
}
# apply to each name
sapply(unique(df1$names), function(name) cons_len(df2, name, 1))
# bob henry maria
# 3 0 2
sapply(unique(df1$names), function(name) cons_len(df2, name, 3))
# bob henry maria
# 0 3 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.