2012-05-31 2 views
2

큰 데이터 세트가 있습니다. 나는 같은 크기 "s"로 각각 "n"개의 하위 데이터 세트로 나누고 싶다. 그러나 번호로 나눌 수없는 경우 마지막 데이터 세트는 다른 크기보다 작을 수 있습니다. csv 파일로 작업 디렉토리에 출력하십시오.임의의 열이 r 인 여러 데이터 세트로 분할 된 데이터 세트

는 다음과 같은 작은 예를 말할 수 있습니다 :

set.seed(1234) 
mydf <- data.frame (matrix(sample(1:10, 130, replace = TRUE), ncol = 13)) 
mydf 

    X1 X2 X3 X4 X5 X6 X7 X8 X9 X10 X11 X12 X13 
1 3 7 1 9 6 4 7 5 8 2 2 2 8 
2 5 3 4 6 9 5 3 10 5 8 10 2 10 
3 4 6 10 4 4 6 3 4 2 9 9 2 9 
4 10 10 9 4 3 7 7 7 10 6 7 10 2 
5 10 3 9 3 2 10 9 6 4 4 4 6 3 
6 7 2 8 7 5 5 10 10 9 3 7 8 4 
7 3 2 2 7 10 9 2 2 10 1 1 10 4 
8 3 9 9 7 3 1 7 6 10 3 10 3 2 
9 9 3 6 9 3 2 2 3 4 2 9 10 10 
10 6 4 3 3 5 9 3 9 10 7 4 6 10 

내가 무작위로 (13 열이 있기 때문에이 경우, 크기 3 말할 n 개의 부분 집합으로의 데이터 집합을 분할하는 함수를 만들려면을 - 마지막 데이터 세트에는 각각 1 개씩 나머지 열이 있습니다. 4) 각각 별도의 데이터 세트로 텍스트 파일로 출력됩니다. 나는 100 개 서브 데이터 셋을 생성하기 위해 가지고

set.seed(123) 
reshuffled <- sample(1:length(mydf),length(mydf), replace = FALSE) 
# just crazy manual divide 
group1 <- reshuffled[1:3]; group2 <- reshuffled[4:6]; group3 <- reshuffled[7:9] 
group4 <- reshuffled[10:12]; group5 <- reshuffled[13] 

# just manual 
data1 <- mydf[,group1]; data2 <- mydf[,group2]; ....so on; 
# I want to write dimension of dataset at fist row of each dataset 
cat (dim(data1)) 
write.csv(data1, "data1.csv"); write.csv(data2, "data2.csv"); .....so on 

는 과정을 반복 할 수 있습니다 : 여기

내가 무슨 짓을?

답변

1

은 아마 깨끗하고 간단한 해결책이있다, 그러나 당신은 다음과 같은 시도 할 수 있습니다 : 그냥 재미를위한

mydf <- data.frame (matrix(sample(1:10, 130, replace = TRUE), ncol = 13)) 

## Number of columns for each sub-dataset 
size <- 3 

nb.cols <- ncol(mydf) 
nb.groups <- nb.cols %/% size 
reshuffled <- sample.int(nb.cols, replace=FALSE) 
groups <- c(rep(1:nb.groups, each=size), rep(nb.groups+1, nb.cols %% size)) 
dfs <- lapply(split(reshuffled, groups), function(v) mydf[,v,drop=FALSE]) 

for (i in 1:length(dfs)) write.csv(dfs[[i]], file=paste("data",i,".csv",sep="")) 
1

보다 아마 더 느린 주바의

mydf <- data.frame (matrix(sample(1:10, 130, replace = TRUE), ncol = 13)) 
size <- 3 
by(t(mydf), 
    INDICES=sample(as.numeric(gl((ncol(mydf) %/% size) + 1, size, ncol(mydf))), 
        ncol(mydf), 
        replace=FALSE), 
    FUN=function(x) write.csv(t(x), paste(rownames(x), collapse='-'), row.names=F)) 
0

에 'mydf'을 분할하기 위해서 n 거의 동일한 부분, 나는이 질문과 그에 대한 대답 에서 영감을 얻었습니다 : link.

가장 작은 파티션과 파티션 사이의 차이가 가능한 한 작은 파티션 크기를 만듭니다. 이 예에서이 차이는 1과 같습니다. 예 :

파티션 방법 1 - 'floor'기능 (여기에 표시된 재현 가능 코드 없음)을 사용합니다. 첫 번째 6 번의 반복에 대해 샘플 바닥 (100/7) = 14 개의 인덱스로 7 개의 거의 동일한 부분/요약에서 100 개의 행을 나눕니다. 7 번째 요소는 나머지 값입니다. 이 수율 :

14, 14, 14, 14, 14, 14, 16 합 = 100, 최대 차이 = 2 분할 방법 2

- 'ceiling' 기능을 사용하여이 (어떤 재생 가능한 코드는 여기에 도시되지).

15, 15, 15, 15, 15, 15, 10 합 = 100, 최대 차분 = 5

파티션 : floor'-함수 '대신의 ceiling' 함수'를 사용하여 유사한 결과를 얻을 방법 3 - 위의 수식을 사용하십시오. 파티션 크기 아래 절차, 벡터 ('sequence_diff')를 사용하는 경우이다

14, 14, 14, 15, 14, 14, 15 합 = 100, 최대 차분 = 1

R- 코드 :

set.seed(1234) 
#I increased the number of rows in the data frame to 100 
mydf <- data.frame (matrix(sample(x = 1:100, size = 1300, replace = TRUE), 
        ncol = 13)) 

index_list  <- list()  #Will store the indices for all partitions 
indices   <- 1:nrow(mydf) #Initially contains all indices for the dataset 'mydf' 
numb_partitions <- 7   #Specifies the number of partitions 

sequence <- floor(((nrow(mydf)*1:numb_partitions)/numb_partitions)) 
sequence <- c(0, sequence) 

#'sequence_diff' will contain the number of instances for each partition. 
sequence_diff <- vector() 
for(j in 1:numb_partitions){ 
    sequence_diff[j] <- sequence[j+1] - sequence[j] 
} 

#Inspect 'sequence_diff' and verify it's elements sum up to the total 
#number of rows in 'mydf' (100). 
> sequence_diff 
[1] 14 14 14 15 14 14 15 
> sum(sequence_diff) 
[1] 100 #Correct! 

for(i in 1:numb_partitions){ 

    #Use a different seed for each sampling iteration. 
    set.seed(seed = i) 

    #Sample from object 'indices' of size 1/'numb_partitions' 
    indices_partition <- sample(x = indices, 
           size = sequence_diff[i], 
           replace = FALSE) 

    #Remove the selected indices from 'indices' so these indices will not be 
    #selected in successive iterations. 
    indices   <- setdiff(x = indices, y = indices_partition) 

    #Store the indices for the i-th iteration in the list 'index_list'. This 
    #is just to verify later that 
    #the procedure has divided all indices in 'numb_partitions' disjunct sets. 
    index_list[[i]] <- indices_partition 

    #Dynamically create a new object that is named 'mydfx' in which x is the 
    #i-th partition. 
    assign(x = paste0("mydf", i), value = mydf[indices_partition,]) 

    write.csv(x = get(x = paste0("mydf", i)), #Dynamically get the object from environment. 
      file = paste0("mydf", i,".csv"), #Dynamically assgin a name to the csv-file. 
      sep = ",", 
      col.names = T, 
      row.names = FALSE  
} 

#Check whether all index subsets are mutually exclusive: union should have 100 
#unique elements. 
length(unique(unlist(index_list))) 
[1] 100 #Correct! 
관련 문제