2011-06-08 39 views
7

我想一個數據幀劃分成基於在一個列中的值的幾個部件dataframes。 在我的例子,我想用值列「電導率」以逸分成dat.1,dat.2和dat.3。 有一個簡單的命令,它可以實現這一目標?如何R中創建組件(子)dataframes基於列值?

dat 
sub cond trial time01 time02 
1 1 1 2774 8845 
1 1 2 2697 9945 
1 2 1 2219 9291 
1 2 2 3886 7890 
1 3 1 4011 9032 
2 2 1 3478 8827 
2 2 2 2263 8321 
2 3 1 4312 7576 
3 1 1 4219 7891 
3 3 1 3992 6674 


dat.1    
sub cond trial time01 time02 
1 1 1 2774 8845 
1 1 2 2697 9945 
3 1 1 4219 7891  

dat.2    
sub cond trial time01 time02 
2 2 1 3478 8827 
2 2 2 2263 8321 
1 2 1 2219 9291 
1 2 2 3886 7890 

dat.3    
sub cond trial time01 time02 
1 3 1 4011 9032 
2 3 1 4312 7576 
3 3 1 3992 6674 

也許是因爲我,我還沒有確定,儘管瀏覽,並試圖在幾個類似的論壇上查詢所提出的解決方案是如何做到這一點的R新手。提前謝謝你的回覆。

A的數據的dput()是:

structure(list(sub = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L 
), cond = c(1L, 1L, 2L, 2L, 3L, 2L, 2L, 3L, 1L, 3L), trial = c(1L, 
2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L), time01 = c(2774L, 2697L, 
2219L, 3886L, 4011L, 3478L, 2263L, 4312L, 4219L, 3992L), time02 = c(8845L, 
9945L, 9291L, 7890L, 9032L, 8827L, 8321L, 7576L, 7891L, 6674L 
)), .Names = c("sub", "cond", "trial", "time01", "time02"), class = "data.frame", row.names = c(NA, 
-10L)) 

回答

7

是否有不符合有關

split(dat, dat$cond) 

什麼? 你確實有R和分裂的標籤,你知道...

+1

+1隊長明顯 – 2011-06-08 13:35:24

6

是,split()。例如,如果你的數據在dat,則:

with(dat, split(dat, cond)) 

返回一個列表,其分量是你想要的數據幀:

R> with(dat, split(dat, cond)) 
$`1` 
    sub cond trial time01 time02 
1 1 1  1 2774 8845 
2 1 1  2 2697 9945 
9 3 1  1 4219 7891 

$`2` 
    sub cond trial time01 time02 
3 1 2  1 2219 9291 
4 1 2  2 3886 7890 
6 2 2  1 3478 8827 
7 2 2  2 2263 8321 

$`3` 
    sub cond trial time01 time02 
5 1 3  1 4011 9032 
8 2 3  1 4312 7576 
10 3 3  1 3992 6674 
+0

您的頭髮打我! – Sam 2011-06-08 11:52:01

+0

@Same @Nick擊敗了我們兩人(如果初始時間正確,我減少了12秒) – 2011-06-08 11:52:54

+0

感謝所有回覆的人。 split()解決了我的問題。我希望在某個時候我可以幫助提供R的幫助。 – dancingRobot 2011-06-08 12:30:38

9

我認爲最簡單的方法是通過split

split(dat, dat$cond) 

不過請注意,那一剎那返回data.frames的列表。

爲了從列表單data.frames你可以PROCEDE使用一個循環,使單個對象(在lapply聲明中隱含的)如下:

tmp <- split(dat, dat$cond) 
lapply(1:length(tmp), function(x) assign(paste("dat.", x, sep = ""), tmp[[x]], envir = .GlobalEnv)) 

然而,使用列表可能更R從長遠來看,它將更加有用。

感謝加文張貼的數據!

+2

增加了'dput()'輸出... :-) – 2011-06-08 11:51:59

4

爲了完整起見,下面是使用plyr包的方法。

require(plyr) 

> dlply(dat, .(cond)) 
$`1` 
    sub cond trial time01 time02 
1 1 1  1 2774 8845 
2 1 1  2 2697 9945 
9 3 1  1 4219 7891 

$`2` 
    sub cond trial time01 time02 
3 1 2  1 2219 9291 
4 1 2  2 3886 7890 
6 2 2  1 3478 8827 
7 2 2  2 2263 8321 

$`3` 
    sub cond trial time01 time02 
5 1 3  1 4011 9032 
8 2 3  1 4312 7576 
10 3 3  1 3992 6674 

attr(,"class") 
[1] "split" "list" 

注意在這句法簡單,你只提dat一次。

0

;)

ucond <- unique(dat$cond) 
dat_by_cond <- lapply(lapply(ucond, "==", dat$cond), subset, x=dat) 
names(dat_by_cond) <- paste("dat",ucond,sep=".")