我有一个类似的数据。
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"
在它们之间。
这里的顺序很重要,因为第一个块指的不是与第二个块相同的东西。
我的数据实际上更复杂,它有第四个变量,指示每一行Account
的含义。每个Account
元素(因子本身)的元素数可以改变。例如,在某些状态下,"In the Bimester"
的第一个“块”可以有6行,第二个可以有7行;但是,我不能用第四个变量来区分。
想要的:我想要子集我的数据,将这两个"In the Bimester"
按每个状态分割,只将第一个“块”的行按每个状态或第二个“块”插入。
我有一个使用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)]
发布于 2017-10-04 13:19:21
您可以使用dplyr
包:
library(dplyr)
B %>% mutate(helper = data.table::rleid(Account)) %>%
filter(Account == "In the Bimester") %>%
group_by(State) %>% filter(helper == min(helper)) %>% select(-helper)
# # A tibble: 6 x 3
# # Groups: State [3]
# State Account Value
# <fctr> <fctr> <dbl>
# 1 Arizona In the Bimester 0.17730148
# 2 Arizona In the Bimester 0.05695585
# 3 California In the Bimester 0.29089678
# 4 California In the Bimester 0.86952723
# 5 Texas In the Bimester 0.54076144
# 6 Texas In the Bimester 0.59168138
如果您不使用min
,而是使用max
,那么您将得到每个State
最后出现的"In the Bimester"
。还可以通过将最后一个管道更改为Account
列来排除select(-helper,-Account)
列。
p.s.如果您不想使用data.table
中的rleid
而只使用dplyr
函数,请查看这个thread。
https://stackoverflow.com/questions/46573724
复制