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

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

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 &lt;- c(25,
       12,
       32,
       52,
       56,
       98,
       96,
       53,
       25,
       22)
df &lt;- data.frame(A = A)

matrix(as.matrix(df), ncol = 5, byrow = TRUE) %&gt;%
  as.data.frame() %&gt;%
  unite(everything(), col = &quot;A&quot;, sep = &quot;,&quot;)
#&gt;                A
#&gt; 1 25,12,32,52,56
#&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

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 %&gt;% 
  group_by(grp = (row_number() - 1) %/% 5) %&gt;%
  summarise(A = paste(A, collapse = &quot;,&quot;))

Result

# A tibble: 2 &#215; 2
    grp A             
  &lt;dbl&gt; &lt;chr&gt;         
1     0 25,12,32,52,56
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:

确定