IT Share you

data.frame의 행을 N 번 반복

shareyou 2020. 11. 29. 12:37
반응형

data.frame의 행을 N 번 반복


다음 데이터 프레임이 있습니다.

data.frame(a = c(1,2,3),b = c(1,2,3))
  a b
1 1 1
2 2 2
3 3 3

그리고 나는 그것을 다음과 같이 바꾸고 싶다.

  a b
1 1 1
2 2 2
3 3 3
4 1 1
5 2 2
6 3 3
7 1 1
8 2 2
9 3 3

또는 N 번 반복합니다. R에서이 작업을 수행하는 쉬운 기능이 있습니까? 감사!


편집 : 더 나은 현대 R 답변으로 업데이트되었습니다.

당신은 사용할 수 있습니다 replicate()다음, rbind(가) 다시 함께 발생합니다. 행 이름은 1 : nrows에서 실행되도록 자동으로 변경됩니다.

d <- data.frame(a = c(1,2,3),b = c(1,2,3))
n <- 3
do.call("rbind", replicate(n, d, simplify = FALSE))

보다 전통적인 방법은 인덱싱을 사용하는 것이지만 여기서 행 이름 변경은 그렇게 깔끔하지는 않지만 더 많은 정보를 제공합니다.

 d[rep(seq_len(nrow(d)), n), ]

다음은 purrr함수형 프로그래밍을 사용하는 처음 두 개 , 관용적 purrr 에 대한 개선 사항입니다 .

purrr::map_dfr(seq_len(3), ~d)

그리고 덜 관용적 인 purrr (더 어색하지만 동일한 결과) :

purrr::map_dfr(seq_len(3), function(x) d)

마지막으로 목록 대신 색인을 통해 dplyr다음을 사용하여 적용하십시오 .

d %>% slice(rep(row_number(), 3))

들어 data.frame객체,이 솔루션은 몇 배 빠른 속도로보다 @ mdsummer의 및 @ 요이치 - sobala의.

d[rep(seq_len(nrow(d)), n), ]

들면 data.table목적, @ mdsummer의 약간 빠르게로 변환 한 후 상기인가보다 data.frame. 큰 n의 경우 이것은 뒤집힐 수 있습니다. 마이크로 벤치 마크.

전체 코드 :

packages <- c("data.table", "ggplot2", "RUnit", "microbenchmark")
lapply(packages, require, character.only=T)

Repeat1 <- function(d, n) {
  return(do.call("rbind", replicate(n, d, simplify = FALSE)))
}

Repeat2 <- function(d, n) {
  return(Reduce(rbind, list(d)[rep(1L, times=n)]))
}

Repeat3 <- function(d, n) {
  if ("data.table" %in% class(d)) return(d[rep(seq_len(nrow(d)), n)])
  return(d[rep(seq_len(nrow(d)), n), ])
}

Repeat3.dt.convert <- function(d, n) {
  if ("data.table" %in% class(d)) d <- as.data.frame(d)
  return(d[rep(seq_len(nrow(d)), n), ])
}

# Try with data.frames
mtcars1 <- Repeat1(mtcars, 3)
mtcars2 <- Repeat2(mtcars, 3)
mtcars3 <- Repeat3(mtcars, 3)

checkEquals(mtcars1, mtcars2)
#  Only difference is row.names having ".k" suffix instead of "k" from 1 & 2
checkEquals(mtcars1, mtcars3)

# Works with data.tables too
mtcars.dt <- data.table(mtcars)
mtcars.dt1 <- Repeat1(mtcars.dt, 3)
mtcars.dt2 <- Repeat2(mtcars.dt, 3)
mtcars.dt3 <- Repeat3(mtcars.dt, 3)

# No row.names mismatch since data.tables don't have row.names
checkEquals(mtcars.dt1, mtcars.dt2)
checkEquals(mtcars.dt1, mtcars.dt3)

# Time test
res <- microbenchmark(Repeat1(mtcars, 10),
                      Repeat2(mtcars, 10),
                      Repeat3(mtcars, 10),
                      Repeat1(mtcars.dt, 10),
                      Repeat2(mtcars.dt, 10),
                      Repeat3(mtcars.dt, 10),
                      Repeat3.dt.convert(mtcars.dt, 10))
print(res)
ggsave("repeat_microbenchmark.png", autoplot(res))

패키지 dplyr에는 bind_rows()목록의 모든 데이터 프레임을 직접 결합 하는 함수 포함되어 있으므로 다음 do.call()과 함께 사용할 필요가 없습니다 rbind().

df <- data.frame(a = c(1, 2, 3), b = c(1, 2, 3))
library(dplyr)
bind_rows(replicate(3, df, simplify = FALSE))

bind_rows()많은 반복의 경우 rbind()다음 보다 훨씬 빠릅니다 .

library(microbenchmark)
microbenchmark(rbind = do.call("rbind", replicate(1000, df, simplify = FALSE)),
               bind_rows = bind_rows(replicate(1000, df, simplify = FALSE)),
               times = 20)
## Unit: milliseconds
##       expr       min        lq      mean   median        uq       max neval cld
##      rbind 31.796100 33.017077 35.436753 34.32861 36.773017 43.556112    20   b
##  bind_rows  1.765956  1.818087  1.881697  1.86207  1.898839  2.321621    20  a 

d <- data.frame(a = c(1,2,3),b = c(1,2,3))
r <- Reduce(rbind, list(d)[rep(1L, times=3L)])

반복 기능과 함께 간단한 인덱싱을 사용하십시오.

mydata<-data.frame(a = c(1,2,3),b = c(1,2,3)) #creating your data frame  
n<-10           #defining no. of time you want repetition of the rows of your dataframe

mydata<-mydata[rep(rownames(mydata),n),] #use rep function while doing indexing 
rownames(mydata)<-1:NROW(mydata)    #rename rows just to get cleaner look of data

더 간단합니다.

library(data.table)
my_data <- data.frame(a = c(1,2,3),b = c(1,2,3))
rbindlist(replicate(n = 3, expr = my_data, simplify = FALSE)

으로 -package, 당신은 특별한 기호 사용할 수 있습니다 .I함께을 함께 rep:

df <- data.frame(a = c(1,2,3), b = c(1,2,3))
dt <- as.data.table(df)

n <- 3

dt[rep(dt[, .I], n)]

다음을 제공합니다.

   a b
1: 1 1
2: 2 2
3: 3 3
4: 1 1
5: 2 2
6: 3 3
7: 1 1
8: 2 2
9: 3 3

참고 URL : https://stackoverflow.com/questions/8753531/repeat-rows-of-a-data-frame-n-times

반응형