生成新行并按顺序在R中填充它们。

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

Generate new rows and fill them in sequentially in R

问题

列 A 列 B
100 1
100 2
100 3
200 1
200 2
200 3
200 4
300 1
英文:

I have a table which currently looks like this:

Column A Column B
100 3
200 4
300 1

From this, I want a table which has new rows created that count from 1 to the value listed in Column B, so:

Column A Column B
100 1
100 2
100 3
200 1
200 2
200 3
200 4
300 1

答案1

得分: 3

可以使用 tidyr::uncount 函数,并通过指定 .id 参数来获取顺序索引。

  1. library(dplyr)
  2. library(tidyr)
  3. df %>% uncount(ColumnB, .id = "ColumnB")
  4. # ColumnA ColumnB
  5. #1 100 1
  6. #2 100 2
  7. #3 100 3
  8. #4 200 1
  9. #5 200 2
  10. #6 200 3
  11. #7 200 4
  12. #8 300 1

data

  1. df <- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L, 4L, 1L)), row.names = c(NA, -3L), class = "data.frame")
英文:

You may use tidyr::uncount by specifying .id argument to get the sequential index.

  1. library(dplyr)
  2. library(tidyr)
  3. df %&gt;% uncount(ColumnB, .id = &quot;ColumnB&quot;)
  4. # ColumnA ColumnB
  5. #1 100 1
  6. #2 100 2
  7. #3 100 3
  8. #4 200 1
  9. #5 200 2
  10. #6 200 3
  11. #7 200 4
  12. #8 300 1

data

  1. df &lt;- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L,
  2. 4L, 1L)), row.names = c(NA, -3L), class = &quot;data.frame&quot;)

答案2

得分: 2

使用repsequence的基本R选项:

  1. with(
  2. df,
  3. data.frame(
  4. ColumnA = rep(ColumnA, ColumnB),
  5. ColumnB = sequence(ColumnB)
  6. )
  7. )

结果:

  1. ColumnA ColumnB
  2. 1 100 1
  3. 2 100 2
  4. 3 100 3
  5. 4 200 1
  6. 5 200 2
  7. 6 200 3
  8. 7 200 4
  9. 8 300 1

数据

  1. df <- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L,
  2. 4L, 1L)), class = "data.frame", row.names = c(NA, -3L))
英文:

A base R option using rep + sequence

  1. with(
  2. df,
  3. data.frame(
  4. ColumnA = rep(ColumnA, ColumnB),
  5. ColumnB = sequence(ColumnB)
  6. )
  7. )

gives

  1. ColumnA ColumnB
  2. 1 100 1
  3. 2 100 2
  4. 3 100 3
  5. 4 200 1
  6. 5 200 2
  7. 6 200 3
  8. 7 200 4
  9. 8 300 1

Data

  1. df &lt;- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L,
  2. 4L, 1L)), class = &quot;data.frame&quot;, row.names = c(NA, -3L))

huangapple
  • 本文由 发表于 2023年6月5日 19:19:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76405906.html
匿名

发表评论

匿名网友

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

确定