gpt4 book ai didi

r - 添加基于零组的 ID

转载 作者:行者123 更新时间:2023-12-05 01:10:08 26 4
gpt4 key购买 nike

我的数据集很大,包含在测试 session 的设定时间段(期间)内对个人(姓名)的许多观察结果(因变量 = DV)。我的数据集的一个小例子如下:

ExampleData <- data.frame(Name = c("Tom","Tom","Tom","Tom","Tom","Tom","Tom","Tom", "Tom", "Tom", 
"Ben","Ben","Ben","Ben","Ben","Ben","Ben","Ben", "Ben", "Ben"),
Period = c(0,0,1,1,1,0,0,0,1,1,
0,0,0,1,1,1,0,0,1,1),
DV = runif(20, 1.5, 2.8))

ExampleData$Period==1 一个人正在进行运动测试时,时间/长度会有所不同。每个测试之间的中断由 ExampleData$Period==0 表示。为避免在某人进行测试时手动输入并在其中添加连续时间段,我希望包括一个列,声明何时由一组 0 分隔的一组 1 是新的时间段 - 跨每个人的数据。请问我该怎么做呢?

我的预期输出是:

ExampleData$Descriptor <- c(NA,NA,"Period One", "Period One","Period One",NA,NA,NA,"Period Two","Period Two",
NA,NA,NA,"Period One","Period One","Period One",NA,NA,"Period Two","Period Two")

我的问题与我的另一个问题类似,位于 here ,尽管我现在每个人都有多个条目。我尝试了以下的 dplyr 语法:

Test_df <- ExampleData %>%
mutate(
Descriptor = case_when(
Period > 0 ~ "Period",
Period == 0 ~ "Rest"),
rleid = cumsum(Descriptor != lag(Descriptor, 1, default = "NA")),
Descriptor = case_when(
Descriptor == "Period" ~ paste0(Descriptor, rleid %/% 2),
TRUE ~ "Rest"),
rleid = NULL
)

尽管如此,我如何解释数据集中每个不同的姓名/个人?

谢谢。

最佳答案

这是 dplyr 的另一种方法

library(dplyr)

ExampleData %>%
group_by(Name) %>%
mutate(Descriptor = with(rle(Period == 1),
rep(replace(paste("Period", cumsum(values)), !values, NA), lengths)))

# # A tibble: 20 x 4
# # Groups: Name [2]
# Name Period DV Descriptor
# <fctr> <dbl> <dbl> <chr>
# 1 Tom 0 2.641044 <NA>
# 2 Tom 0 2.692745 <NA>
# 3 Tom 1 1.515797 Period 1
# 4 Tom 1 2.601471 Period 1
# 5 Tom 1 1.669399 Period 1
# 6 Tom 0 2.700371 <NA>
# 7 Tom 0 1.993971 <NA>
# 8 Tom 0 2.203379 <NA>
# 9 Tom 1 2.488742 Period 2
# 10 Tom 1 1.596458 Period 2
# 11 Ben 0 2.578924 <NA>
# 12 Ben 0 1.916804 <NA>
# 13 Ben 0 2.676466 <NA>
# 14 Ben 1 2.508759 Period 1
# 15 Ben 1 2.447217 Period 1
# 16 Ben 1 2.728756 Period 1
# 17 Ben 0 2.326854 <NA>
# 18 Ben 0 1.748016 <NA>
# 19 Ben 1 1.703044 Period 2
# 20 Ben 1 1.783434 Period 2

关于r - 添加基于零组的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46110280/

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