替代 expand.grid for data.frames [英] Alternative to expand.grid for data.frames

查看:39
本文介绍了替代 expand.grid for data.frames的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame df 并且我希望这个 df 中的每一行都被复制 lengthTime 次,并且一个新列是添加了 df 中每一行从 1 到 lengthTime 的计数.

I have a data.frame df and I want that every row in this df is duplicated lengthTime times and that a new column is added that counts from 1 to lengthTime for each row in df.

我知道,这听起来很复杂,但我基本上想要的是将 expand.grid 应用到 df.这是一个丑陋的解决方法,我觉得有一个更简单的解决方案(甚至可能是 base-R 函数?):

I know, it sounds pretty complicated, but what I basically want is to apply expand.grid to df. Here is an ugly workaround and I have the feeling that there most be an easier solution (maybe even a base-R function?):

df <- data.frame(ID   = rep(letters[1:3], each=3),
                 CatA = rep(1:3, times = 3),
                 CatB = letters[1:9])
lengthTime <- 3
nrRow <- nrow(df)
intDF <- df
for (i in 1:(lengthTime - 1)) {
  df <- rbind(df, intDF)
}
df$Time <- rep(1:lengthTime, each=nrRow)

我以为我可以只使用 expand.grid(df, 1:lengthTime),但这不起作用.outer 也没有带来任何运气.那么有人知道一个好的解决方案吗?

I thought that I could just use expand.grid(df, 1:lengthTime), but that does not work. outer did not bring any luck either. So does anyone know a good solution?

推荐答案

为什么不只是像 df[rep(1:nrow(df),times = 3),] 这样的东西来扩展数据框架,然后像上面一样添加额外的列,使用 df$Time <- rep(1:lengthTime, each=nrRow)?

Why not just something like df[rep(1:nrow(df),times = 3),] to extend the data frame, and then add the extra column just as you have above, with df$Time <- rep(1:lengthTime, each=nrRow)?

这篇关于替代 expand.grid for data.frames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆