我有一个包含数字的表1。我想创建行数来自Total列的行。其他列值将根据表1列值随机创建。例如,表2的column1值应具有3个“ 1”值,其余值应为“ 0”。有谁可以帮助我吗?
表1
Year Age Total column1 column2 column3
2017 15 10 3 4 2
所需表
Year Age Total column1 column2 column3
2017 15 1 1 0 0
2017 15 1 0 1 0
2017 15 1 0 0 1
2017 15 1 0 0 1
2017 15 1 1 0 0
2017 15 1 0 1 0
2017 15 1 1 0 0
2017 15 1 0 1 0
2017 15 1 0 1 0
2017 15 1 0 0 0
答案 0 :(得分:1)
与其具有相互排斥的二进制条目的三列,不如将其从宽格式转换为长格式然后进行扩展,可能会更简单:
df<-data.frame(year=2017,age=15,col1=3,col2=4,col3=2)
library(dplyr)
library(tidyr)
df %>%
gather('key','value',col1:col3) %>%
# year age key value
# 1 2017 15 col1 3
# 2 2017 15 col2 4
# 3 2017 15 col3 2
filter(value>0) %>% # Avoid keys with 0 values
group_by(year,age,key) %>%
expand(value=1:value)%>%
# year age key value
# <dbl> <dbl> <chr> <int>
# 1 2017 15 col1 1
# 2 2017 15 col1 2
# 3 2017 15 col1 3
# 4 2017 15 col2 1
# 5 2017 15 col2 2
# 6 2017 15 col2 3
# 7 2017 15 col2 4
# 8 2017 15 col3 1
# 9 2017 15 col3 2
ungroup()%>%select(-value)
# # A tibble: 9 x 3
# year age key
# <dbl> <dbl> <chr>
# 1 2017 15 col1
# 2 2017 15 col1
# 3 2017 15 col1
# 4 2017 15 col2
# 5 2017 15 col2
# 6 2017 15 col2
# 7 2017 15 col2
# 8 2017 15 col3
# 9 2017 15 col3