B <- data.frame(State = c(rep("Arizona", 8), rep("California", 8), rep("Texas", 8)),
Account = rep(c("Balance", "Balance", "In the Bimester", "In the Bimester", "Expenses",
"Expenses", "In the Bimester", "In the Bimester"), 3), Value = runif(24))
Account
元素出现4次
"In the Bimester"
,
每个状态有两个元素,
"Expenses"
这里的顺序很重要,因为第一个块与第二个块指的不是同一个东西。
账户
方法每个元素的元素数
账户
元素(因子本身)可以更改。例如,在某些状态下
“在双酯中”
可以有6行和第二行,7行;但是,我不能用这个第四个变量来区分。
渴望的:
我想对我的数据进行子集,将它们分开
按每个状态,仅按每个状态或第二个“块”将第一个“块”的行子集。
我有一个解决方案,使用
data.table
library(data.table)
B <- as.data.table(B)
B <- B[, .(Account, Value, index = 1:.N), by = .(State)]
x <- B[Account == "Expenses", .(min_ind = min(index)), by = .(State)]
B <- merge(B, x, by = "State")
B <- B[index < min_ind & Account == "In the Bimester", .(Value), by = .(State)]