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

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

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 参数来获取顺序索引。

library(dplyr)
library(tidyr)

df %>% uncount(ColumnB, .id = "ColumnB")

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

data

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.

library(dplyr)
library(tidyr)

df %&gt;% uncount(ColumnB, .id = &quot;ColumnB&quot;)

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

data

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

答案2

得分: 2

使用repsequence的基本R选项:

with(
    df,
    data.frame(
        ColumnA = rep(ColumnA, ColumnB),
        ColumnB = sequence(ColumnB)
    )
)

结果:

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

数据

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

A base R option using rep + sequence

with(
    df,
    data.frame(
        ColumnA = rep(ColumnA, ColumnB),
        ColumnB = sequence(ColumnB)
    )
)

gives

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

Data

df &lt;- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L,
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:

确定