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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.