复制每一行数据.帧,并指定每一行的复制数量

复制每一行数据.帧,并指定每一行的复制数量

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

最简单的方法是展开上面data.framework的前两列,以便每行显示列‘freq’中指定的次数?


换句话说,从这一点出发:


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


慕雪6442864
浏览 950回答 4
4回答

犯罪嫌疑人X

这里有一个解决方案:df.expanded <- df[rep(row.names(df), df$freq), 1:2]结果:&nbsp; &nbsp; var1 var21&nbsp; &nbsp; &nbsp; a&nbsp; &nbsp; d2&nbsp; &nbsp; &nbsp; b&nbsp; &nbsp; e2.1&nbsp; &nbsp; b&nbsp; &nbsp; e3&nbsp; &nbsp; &nbsp; c&nbsp; &nbsp; f3.1&nbsp; &nbsp; c&nbsp; &nbsp; f3.2&nbsp; &nbsp; c&nbsp; &nbsp; f

慕尼黑5688855

使用expandRows()从splitstackshape一揽子:library(splitstackshape)expandRows(df, "freq")简单的语法,非常快,工作在data.frame或data.table.结果:&nbsp; &nbsp; var1 var21&nbsp; &nbsp; &nbsp; a&nbsp; &nbsp; d2&nbsp; &nbsp; &nbsp; b&nbsp; &nbsp; e2.1&nbsp; &nbsp; b&nbsp; &nbsp; e3&nbsp; &nbsp; &nbsp; c&nbsp; &nbsp; f3.1&nbsp; &nbsp; c&nbsp; &nbsp; f3.2&nbsp; &nbsp; c&nbsp; &nbsp; f

莫回无

旧疑问句中的新动词:library(tidyr) # version >= 0.8.0df <- data.frame(var1=c('a', 'b', 'c'), var2=c('d', 'e', 'f'), freq=1:3)df %>%&nbsp;&nbsp; uncount(freq)&nbsp; &nbsp; var1 var21&nbsp; &nbsp; &nbsp; a&nbsp; &nbsp; d2&nbsp; &nbsp; &nbsp; b&nbsp; &nbsp; e2.1&nbsp; &nbsp; b&nbsp; &nbsp; e3&nbsp; &nbsp; &nbsp; c&nbsp; &nbsp; f3.1&nbsp; &nbsp; c&nbsp; &nbsp; f3.2&nbsp; &nbsp; c&nbsp; &nbsp; f

冉冉说

不是为了data.table因为他们缺少row.names财产。这种方法适用于以下两种情况:df.expanded <- df[rep(seq(nrow(df)), df$freq), 1:2]密码data.table是一点清洁剂:# convert to data.table by referencesetDT(df)df.expanded <- df[rep(seq(.N), freq), !"freq"]
打开App,查看更多内容
随时随地看视频慕课网APP