重复data.frame的每一行,在列中指定的次数 [英] Repeat each row of data.frame the number of times specified in a column

查看:285
本文介绍了重复data.frame的每一行,在列中指定的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'),
                 freq = 1:3)

最简单的方法是在上述data.frame的前两列中扩展每一行,以使每一行重复在"freq"列中指定的次数?

What is the simplest way to expand each row the first two columns of the data.frame above, so that each row is repeated the number of times specified in the column 'freq'?

换句话说,从这里开始:

In other words, go from this:

df
  var1 var2 freq
1    a    d    1
2    b    e    2
3    c    f    3

对此:

df.expanded
  var1 var2
1    a    d
2    b    e
3    b    e
4    c    f
5    c    f
6    c    f

推荐答案

这里是一种解决方案:

df.expanded <- df[rep(row.names(df), df$freq), 1:2]

结果:

    var1 var2
1      a    d
2      b    e
2.1    b    e
3      c    f
3.1    c    f
3.2    c    f

这篇关于重复data.frame的每一行,在列中指定的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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