英文:
Why does slice_head return too many rows, specifically more than the 'n' I specified?
问题
当创建一个包含7行的数据框时,我想要返回数据框的第一行。
df <- tibble(
group = rep(c("b", "c", "a"), c(1, 2, 4)),
x = runif(7)
)
df
当我进行切片时,每个组返回一行,但我只想返回一行。
df %>%
group_by(group) %>%
slice_head(n = 1)
如何只返回一行?
英文:
When making a dataframe of 7 rows I want to return the first row of the dataframe.
df <- tibble(
group = rep(c("b", "c", "a"), c(1, 2, 4)),
x = runif(7)
)
df
# A tibble: 7 × 2
group x
<chr> <dbl>
1 b 0.269
2 c 0.0697
3 c 0.705
4 a 0.772
5 a 0.513
6 a 0.841
7 a 0.896
When I slice, a row per group is returned but I only want one row returned.
df %>%
group_by(group) %>%
slice_head(n = 1)
# A tibble: 3 × 2
# Groups: group [3]
group x
<chr> <dbl>
1 a 0.772
2 b 0.269
3 c 0.0697
How can I return only one row?
答案1
得分: 3
这个问题可以通过取消对数据框进行分组来解决。
解决方案:
df %>%
group_by(group) %>%
ungroup() %>%
slice_head(n = 1)
# A tibble: 1 × 2
group x
<chr> <dbl>
1 b 0.269
(请注意,这是一段R代码,其中包含了一些数据框操作,不需要翻译的部分已经保留原文。)
英文:
This can be solved by ungrouping your dataframe.
Solution:
df %>%
group_by(group) %>%
ungroup() %>%
slice_head(n = 1)
# A tibble: 1 × 2
group x
<chr> <dbl>
1 b 0.269
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论