2016-05-05 28 views

回答

0

這個怎麼樣的做法?

# Create data for example 
x <- data.frame(id = 1:100, y = rnorm(100), z = rnorm(100)) 

# Returns a list with four equally sized distinct samples of the data 
lapply(split(sample(nrow(x)), ceiling((1:nrow(x))/25)), function(i) x[i, ]) 
+0

非常感謝你 – Reelina

0

人們可以使用剪切命令:

x<-1:100 
cutindex<-cut(x, breaks=4) 

要重命名的切點使用的「級別」的命令:

levels(cutindex)<-c("A", "B", "C", "D") 

一旦數據已被切斷,我會建議使用dplyr包中的group_by命令進行其他分析。

+0

非常感謝... – Reelina

1

這實際上取決於你的目標是什麼,你可能想在這裏嘗試。我將假設給定一個數據框,你想創建四個相同大小的子集,其中每個子集是隨機採樣的數據四分之一。

爲了便於演示,我使用了包含在基本R中的Seatbelts數據,因爲它的行數是4的倍數。此解決方案僅使用基本R函數。對於更多涉及的數據幀操作,我建議查看dplyr包。

# use seat belts data as example as it has nrow(x) %% 4 == 0 
data(Seatbelts) 
# generate a random sample of numbers 1:4 such that each occurs equally 
ind = sample(rep(1:4,each = nrow(Seatbelts)/4)) 
# you could add that as a column to your data frame allowing the groups to be 
# specified in formulae etc 
# or if you want the four subsets 
lapply(split(1:nrow(Seatbelts),ind), function(i) Seatbelts[i,]) 

如果你的數據是一個矢量,那麼這是比較容易

x = runif(24) 
ind = sample(rep(1:4,each = length(x)/4)) 
split(x,ind) 

如果你不想隨機抽樣然後就創建ind作爲

ind = rep(1:4,each = length(x)/4) 

,並以同樣的方式分像之前一樣。

你應該小心使用像cut這樣的東西,因爲這不會給你4個相同大小的子集。

table(as.numeric(cut(x,4))) 

# 1 2 3 4 
# 7 6 3 8 

這是因爲cut會將x的範圍縮小爲區間而不是長度。

+0

謝謝。這是非常有用的.. – Reelina

+0

沒問題,如果它解決了你的問題,你應該接受答案,以便將來的搜索者可以看到它已被解決。如果你想使用外部包,'caret :: createFolds'可以完成與單個函數調用相同的工作,而不用擔心指定上面的所有額外的東西。 – jamieRowen

相關問題