当前位置: 动力学知识库 > 问答 > 编程问答 >

Replicate entries in DataFrame in R

问题描述:

I have a dataframe of company names: (names)

 names

1 3M CO

2 ABBOTT LABORATORIES

3 ABBVIE INC

4 ACCENTURE PLC

5 ACE LTD

6 ACTAVIS PLC

I want to replicate each entry 5 times so I have:

 names

1 3M CO

1 3M CO

1 3M CO

1 3M CO

1 3M CO

2 ABBOTT LABORATORIES

2 ABBOTT LABORATORIES

2 ABBOTT LABORATORIES

2 ABBOTT LABORATORIES

2 ABBOTT LABORATORIES

3 ABBVIE INC

3 ABBVIE INC

3 ABBVIE INC

3 ABBVIE INC

3 ABBVIE INC

......

I have tried append, and rep but think I may need a for loop?

网友答案:

You can in fact use rep:

d <- data.frame(x = letters[1:5])
> d
  x
1 a
2 b
3 c
4 d
5 e

> d[rep(seq_len(nrow(d)),each = 5),,drop = FALSE]
    x
1   a
1.1 a
1.2 a
1.3 a
1.4 a
2   b
2.1 b
2.2 b
2.3 b
2.4 b
3   c
3.1 c
3.2 c
3.3 c
3.4 c
4   d
4.1 d
4.2 d
4.3 d
4.4 d
5   e
5.1 e
5.2 e
5.3 e
5.4 e
网友答案:

Here's an example using plyr.

library(plyr)

myDF <- data.frame(
    names=c('3M CO', 'ABBOTT LABORATORIES', 'ABBVIE INC', 
            'ACCENTURE PLC', 'ACE LTD', 'ACTAVIS PLC'),
    stringsAsFactors=FALSE
)

myfun <- function(x) {
    dat <- rep(x$names, times=5)
    return(data.frame(names=dat, stringsAsFactors=FALSE))
}

newDF <- ddply(myDF, 'names', myfun)
分享给朋友:
您可能感兴趣的文章:
随机阅读: