【发布时间】:2022-01-05 09:49:19
【问题描述】:
在这个数据框中:
df <- data.frame(
PP_by = c("A","B","A","A","B","B", rep("C",2),"A","A","A","B"),
Sequ = c(1,1,1,1,1,1,4,4,4,4,4,4),
Line = c(55,55,77,77,77,77,99,99,99,99,33,33),
pp = rnorm(12),
pp2 = c(1.1,1.2,1.1,1.2,1.3,1.5,1.3,1.2,1.5,1.7,1.0,1.9),
other = 1:12,
other2 = letters[1:12]
)
我想用Sequ 和Line 分组的第一个值对行进行切片。我试过了,但它返回空:
df %>%
group_by(Sequ) %>%
slice(first(Line))
# A tibble: 0 × 7
# Groups: Sequ [0]
# … with 7 variables: PP_by <chr>, Sequ <dbl>, Line <dbl>, pp <dbl>, pp2 <dbl>, other <int>, other2 <chr>
想要的结果是这样的:
df
PP_by Sequ Line pp pp2 other other2
1 A 1 55 0.30277770 1.1 1 a
2 B 1 55 1.55909373 1.2 2 b
7 C 4 99 1.33796806 1.3 7 g
8 C 4 99 -0.23230445 1.2 8 h
9 A 4 99 -0.12740409 1.5 9 i
10 A 4 99 -0.02168540 1.7 10 j
【问题讨论】: