gpt4 book ai didi

r - 如何根据条件删除数据框的 N 行

转载 作者:行者123 更新时间:2023-12-04 11:36:15 28 4
gpt4 key购买 nike

我的问题来自 How to find tail rows of a data frame that satisfy set criteria?因此,我的(更新的)示例数据的结构如下:

Individ <- data.frame(Participant = c("Bill", "Bill", "Bill", "Bill", "Bill", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Bill", "Bill", "Bill", "Bill"),  
Time = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4),
Condition = c("Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr", "Expr", "Expr", "Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Placebo", "Expr", "Expr", "Expr", "Expr"),
Location = c("Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Away", "Away", "Away", "Away"),
Power = c(400, 250, 180, 500, 300, 600, 512, 300, 500, 450, 200, 402, 210, 130, 520, 310, 451, 608, 582, 390, 570))

我学会了根据每个 Participant 最后一次出现的 在不同的 Condition 加上 Location 中找到尾行电源。我现在希望针对每个 ConditionLocation 从每个 Participant 中删除最后 3 行。但是,为每个 ParticipantCondition 收集的 Time 不同,因此我不能完全基于标准化的 Time

如何快速遍历每个 Participant 及其各自的 Condition 加上 Location 并删除最后 3 行?我的实际数据框是 400 万行 + 超过 50 个参与者,因此理想情况下,迭代每个 ParticipantCondition 的解决方案将是可取的。

我的预期输出是:

Output <- data.frame(Participant = c("Bill", "Bill", "Jane", "Jane", "Jane", "Jane", "Jane", "Jane", "Bill"),
Time = c(1, 2, 1, 2, 3, 1, 2, 3, 1),
Condition = c("Placebo", "Placebo", "Expr", "Expr", "Expr", "Placebo", "Placebo", "Placebo", "Expr"),
Location = c("Home", "Home", "Home", "Home", "Home", "Home", "Home", "Home", "Away"),
Power = c(400, 250, 600, 512, 300, 402, 210, 130, 608))

最佳答案

如果你使用dplyr,用row_number()n()...

library(dplyr)
Individ %>%
group_by(Participant, Condition, Location) %>%
filter(row_number() < n() - 2)

返回

Source: local data frame [9 x 5]
Groups: Participant, Condition, Location [4]

Participant Time Condition Location Power
(fctr) (dbl) (fctr) (fctr) (dbl)
1 Bill 1 Placebo Home 400
2 Bill 2 Placebo Home 250
3 Jane 1 Expr Home 600
4 Jane 2 Expr Home 512
5 Jane 3 Expr Home 300
6 Jane 1 Placebo Home 402
7 Jane 2 Placebo Home 210
8 Jane 3 Placebo Home 130
9 Bill 1 Expr Away 608

关于r - 如何根据条件删除数据框的 N 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35544180/

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