如何填充数据直到最后一个非缺失值? [英] How do I fill data until last non-missing value?
本文介绍了如何填充数据直到最后一个非缺失值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些数据按let分组:
I have some data grouped by let like so:
events <- structure(list(let = c("A", "A", "A", "B", "B", "B"), age = c(0L,
4L, 16L, 0L, 8L, 7L), value = c(61L, 60L, 13L, 29L, 56L, 99L)),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
let age value
1 A 0 61
2 A 4 60
3 A 16 13
4 B 0 29
5 B 8 56
6 B 7 99
我该如何投射数据框,以便:
How can I cast the data frame so that:
- 年龄是分为几周的多列.因此,对于每一列,取小于或等于0、7、14等天的最大年龄的值
- 直到
let
填满最后一个非缺失值.
- Age is multiple columns grouped into weeks. So for each column, take the value of the largest age that is less than or equal to 0, 7, 14, etc. days
- Fill in age UNTIL the last non-missing value by
let
.
最终结果如下:
events.cast <- data.frame(
let = LETTERS[1:2],
T0_value = c(61,29),
T1_value = c(60,99),
T2_value = c(60,56),
T3_value = c(13,56))
let T0_value T1_value T2_value T3_value
1 A 61 60 60 13
2 B 29 99 56 NA
请注意,这来自上一个问题我问.
推荐答案
我们可以在complete
之前创建一个'actuals'列,并根据发生的情况使用它在'value'列中创建NA
NA
在事实"中
We could create a column of 'actuals' before the complete
and use that to create the NA
in 'value' column based on the occurrence of NA
in 'actuals'
library(dplyr)
library(tidyr)
library(stringr)
events %>%
group_by(grp = cut(age, breaks = c(-Inf,0, 7, 14, 21),
labels = str_c("T", 0:3, "_value")), let) %>%
slice(which.max(value)) %>%
ungroup %>%
select(-age) %>%
mutate(actuals = TRUE) %>%
group_by(let) %>%
complete(grp = unique(.$grp)) %>%
fill(value) %>%
ungroup %>%
mutate(i1 = cumsum(is.na(actuals)),
value = replace(value, i1 == max(i1), NA)) %>%
select(-i1, -actuals) %>%
pivot_wider(names_from = grp, values_from = value)
# A tibble: 2 x 5
# let T0_value T1_value T2_value T3_value
# <chr> <int> <int> <int> <int>
#1 A 61 60 60 13
#2 B 29 99 56 NA
这篇关于如何填充数据直到最后一个非缺失值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文