英文:
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 %>% 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")
答案2
得分: 2
使用rep
和sequence
的基本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 <- structure(list(ColumnA = c(100L, 200L, 300L), ColumnB = c(3L,
4L, 1L)), class = "data.frame", row.names = c(NA, -3L))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论