gpt4 book ai didi

r - 如何将数据转换为非 equi 列?

转载 作者:行者123 更新时间:2023-12-04 10:52:40 27 4
gpt4 key购买 nike

我有一个事件数据集,按 let 分组像这样:

set.seed(3)
events <- data.frame(
let = rep(LETTERS[1:2], each=3),
age = c(0,sample(1:20, size=2),
0,sample(1:20, size=2)),
value = sample(1:100, size=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

如何转换数据框,以便年龄是多列分组为周?因此,对于每一列,取小于或等于 0、7、14、21 天的最大年龄值。
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 56

最佳答案

一种选择是cut将“年龄”放入桶中,获取 max按该组和“让”行,然后 reshape 为“宽”格式

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) %>%
group_by(let) %>%
complete(grp = unique(.$grp)) %>%
fill(value) %>%
pivot_wider(names_from = grp, values_from = value)
# A tibble: 2 x 5
# Groups: let [2]
# 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 56

数据
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"))

关于r - 如何将数据转换为非 equi 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59397169/

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