将行按递增合并为逗号分隔的行

huangapple go评论84阅读模式
英文:

Combining Rows into Comma Separated Rows by Increments

问题

  1. 考虑下面的数据框。
  2. A
  3. 25
  4. 12
  5. 32
  6. 52
  7. 56
  8. 98
  9. 96
  10. 53
  11. 25
  12. 22
  13. 我想将每隔5行的值转换成一个新列,用逗号分隔,如下所示。
  14. A
  15. 25,12,32,52,56
  16. 98,96,53,25,22
  17. 我一直在尝试使用dplyr/mutate,但没有取得太多成功。在R中是否可以实现这个目标?
  18. temp_df <- temp_df %>%
  19. dplyr::summarise(duration = paste(duration, collapse = ","))
英文:

Consider the dataframe below.

  1. A
  2. 25
  3. 12
  4. 32
  5. 52
  6. 56
  7. 98
  8. 96
  9. 53
  10. 25
  11. 22

I would like to transform N rows in increments of 5 into a new column where the values are comma seperated, like below.

  1. A
  2. 25,12,32,52,56
  3. 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()函数,例如:

  1. library(tidyr)
  2. A <- c(25,
  3. 12,
  4. 32,
  5. 52,
  6. 56,
  7. 98,
  8. 96,
  9. 53,
  10. 25,
  11. 22)
  12. df <- data.frame(A = A)
  13. matrix(as.matrix(df), ncol = 5, byrow = TRUE) %>%
  14. as.data.frame() %>%
  15. unite(everything(), col = "A", sep = ",")
  16. #> A
  17. #> 1 25,12,32,52,56
  18. #> 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.

  1. library(tidyr)
  2. A &lt;- c(25,
  3. 12,
  4. 32,
  5. 52,
  6. 56,
  7. 98,
  8. 96,
  9. 53,
  10. 25,
  11. 22)
  12. df &lt;- data.frame(A = A)
  13. matrix(as.matrix(df), ncol = 5, byrow = TRUE) %&gt;%
  14. as.data.frame() %&gt;%
  15. unite(everything(), col = &quot;A&quot;, sep = &quot;,&quot;)
  16. #&gt; A
  17. #&gt; 1 25,12,32,52,56
  18. #&gt; 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

  1. df %>%
  2. group_by(grp = (row_number() - 1) %/% 5) %>%
  3. summarise(A = paste(A, collapse = ","))
  4. Result
  5. # A tibble: 2 × 2
  6. grp A
  7. <dbl> <chr>
  8. 1 0 25,12,32,52,56
  9. 2 1 98,96,53,25,22
英文:
  1. df %&gt;%
  2. group_by(grp = (row_number() - 1) %/% 5) %&gt;%
  3. summarise(A = paste(A, collapse = &quot;,&quot;))

Result

  1. # A tibble: 2 &#215; 2
  2. grp A
  3. &lt;dbl&gt; &lt;chr&gt;
  4. 1 0 25,12,32,52,56
  5. 2 1 98,96,53,25,22

huangapple
  • 本文由 发表于 2023年2月14日 08:13:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定