英文:
Combining Rows into Comma Separated Rows by Increments
问题
考虑下面的数据框。
A
25
12
32
52
56
98
96
53
25
22
我想将每隔5行的值转换成一个新列,用逗号分隔,如下所示。
A
25,12,32,52,56
98,96,53,25,22
我一直在尝试使用dplyr/mutate,但没有取得太多成功。在R中是否可以实现这个目标?
temp_df <- temp_df %>%
dplyr::summarise(duration = paste(duration, collapse = ","))
英文:
Consider the dataframe below.
A
25
12
32
52
56
98
96
53
25
22
I would like to transform N rows in increments of 5 into a new column where the values are comma seperated, like below.
A
25,12,32,52,56
98,96,53,25,22
I have been playing around with dplyr/mutate but have not had much success. Is this possible to do in R?
temp_df <- temp_df %>%
dplyr::summarise(duration = paste(duration, collapse = ","))
答案1
得分: 1
以下是翻译好的内容:
一个潜在的选项是将数据框转换为矩阵,然后使用tidyr包中的unite()
函数,例如:
library(tidyr)
A <- c(25,
12,
32,
52,
56,
98,
96,
53,
25,
22)
df <- data.frame(A = A)
matrix(as.matrix(df), ncol = 5, byrow = TRUE) %>%
as.data.frame() %>%
unite(everything(), col = "A", sep = ",")
#> A
#> 1 25,12,32,52,56
#> 2 98,96,53,25,22
创建于2023-02-14,使用reprex v2.0.2
请注意,这仅在您的列数是5的倍数时有效(即,20行可以工作,21行不行)。
英文:
One potential option is to convert the dataframe into a matrix then use unite()
from the tidyr package, e.g.
library(tidyr)
A <- c(25,
12,
32,
52,
56,
98,
96,
53,
25,
22)
df <- data.frame(A = A)
matrix(as.matrix(df), ncol = 5, byrow = TRUE) %>%
as.data.frame() %>%
unite(everything(), col = "A", sep = ",")
#> A
#> 1 25,12,32,52,56
#> 2 98,96,53,25,22
<sup>Created on 2023-02-14 with reprex v2.0.2</sup>
NB this will only work if your column is a multiple of 5 (i.e. 20 rows will work, 21 rows won't)
答案2
得分: 1
df %>%
group_by(grp = (row_number() - 1) %/% 5) %>%
summarise(A = paste(A, collapse = ","))
Result
# A tibble: 2 × 2
grp A
<dbl> <chr>
1 0 25,12,32,52,56
2 1 98,96,53,25,22
英文:
df %>%
group_by(grp = (row_number() - 1) %/% 5) %>%
summarise(A = paste(A, collapse = ","))
Result
# A tibble: 2 × 2
grp A
<dbl> <chr>
1 0 25,12,32,52,56
2 1 98,96,53,25,22
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论