[英]Add a row for each month for each id in R
So I have a list of IDs. 所以我有一个ID列表。
I would like to create a table consisting of rows for each month of a year for each id in the list. 我想为表中的每个ID创建一个由一年中每个月的行组成的表。
I tried to use a rbind in a for loop but this takes forever... as such: 我试图在for循环中使用rbind,但这需要永远...
for (k in seq_along(members))
{
for (i in seq(1,12))
{
df1<-rbind(df1, data.frame(MemYearMo=paste(members[k],"_",year,formatC(i,width=2,flag=0), sep="")))
}
}
where members is obviously my list of id's. 成员显然是我的ID列表。
My desired output is: XXX_201701 XXX_201702 XXX_201703 . 我想要的输出是:XXX_201701 XXX_201702 XXX_201703。 .
。 .
。 XXX 201712
XXX 201712
where XXX is one of my id's. 其中XXX是我的ID之一。
What would be the fastest way to do something like this? 做这样的最快的方法是什么?
I'm not sure I understand your desired output but you can use expand.grid
to generate the different combinations of member ids with the months of the year. 我不确定我是否了解您想要的输出,但是您可以使用
expand.grid
生成会员ID与一年中不同月份的组合。
Example 例
df <- as.data.frame(expand.grid(members = 901:903, ym = 201701:201712))
df$MemYearMo <- paste(df$members, df$ym, sep = "_")
df
#> members ym MemYearMo
#> 1 901 201701 901_201701
#> 2 902 201701 902_201701
#> 3 903 201701 903_201701
#> 4 901 201702 901_201702
#> 5 902 201702 902_201702
#> 6 903 201702 903_201702
#> ...(and so on)...
#> 34 901 201712 901_201712
#> 35 902 201712 902_201712
#> 36 903 201712 903_201712
Using data.table and paste0 you can do this, assuming that your id's are unique. 假设您的ID是唯一的,则可以使用data.table和paste0进行此操作。
id <- as.data.table(letters)
id <- id[, .(output = paste0(letters, paste0("_2017", c(paste0(0, 1:9), 10:12)))), by = .(letters)]
Using rep
: 使用
rep
:
id <- letters[1:10]
month <- 201701:201712
ids <- rep(ids, each=length(month))
months <- rep(months, length.out=length(id))
data.frame(id=ids, ym=months, id_ym = paste(ids, months, sep="_"))
gives 给
id ym id_ym
1 a 201701 a_201701
2 a 201702 a_201702
3 a 201703 a_201703
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.