2016-03-30 50 views
1

這可能是一個新手問題,但我到處搜索,找不到辦法做到這一點。我有R中的數據幀,看起來像這樣:通過因素級別操縱數據幀

Target Sample Regulation 
AKT1 00h 1.00000 
AKT1 02h 1.27568 
AKT1 06h -1.29813 
AKT1 12h 1.12357 
AKT1 48h 1.02284 
AKT2 00h 1.00000 
AKT2 02h 1.08692 
AKT2 06h 1.19489 
AKT2 12h -1.07677 
AKT2 48h -1.18955 

數據$ Target和數據$樣品是類=因素

我需要創建一個表,如下所示:

Target/Sample AKT1  AKT2 
00h   1.00000 1.00000 
02h   1.27568 1.08692 
06h   -1.29813 1.19489 
12h   1.12357 -1.07677 
48h   1.02284 -1.18955 

換句話說,我需要創建一個新的數據框,其中的列是數據$目標級別,行是數據$樣本級別,並用數據$ Regulation中的相應值填充它。

這是我能想出:

newdata <- data.frame(Time=levels(data$Sample), 
AKT1=as.numeric(data$Regulation[which(dat$Target=="AKT1",)])) 

但我當然不希望由一個自DAT $目標去一個有> 100級(基因)。請幫助!

非常感謝大家!

+1

嘗試尋找在reshape2包 –

+0

dcast這是一個很好的鏈接http://www.cookbook-r.com/ Manipulating_data/Converting_data_between_wide_and_long_format/ – MLavoie

回答

0

您需要從長格式轉換爲寬格式。下面是使用reshape一種替代方案:

reshape(df, idvar = "Sample", timevar = "Target", direction = "wide") 
    Sample Regulation.AKT1 Regulation.AKT2 
1 00h   1.00000   1.00000 
2 02h   1.27568   1.08692 
3 06h  -1.29813   1.19489 
4 12h   1.12357  -1.07677 
5 48h   1.02284  -1.18955 
+0

正是我需要的。十分感謝! – user3803664

+0

@ user3803664不客氣:-) – DatamineR

+0

@ user3803664 - 或者使用'reshape2' - 'reshape2 :: dcast(data,Sample〜Target,value.var =「Regulation」)''。參見[reshape vs. reshape2](http://stackoverflow.com/a/12379002/5977215) – SymbolixAU

0

我們可以使用tidyr

library(tidyr) 
spread(df1, Target, Regulation) 
# Sample  AKT1  AKT2 
#1 00h 1.00000 1.00000 
#2 02h 1.27568 1.08692 
#3 06h -1.29813 1.19489 
#4 12h 1.12357 -1.07677 
#5 48h 1.02284 -1.18955