2015-07-21 31 views
0

我已經在列表下面的示例數據稱爲dataR:拆分列表中列和轉化爲新的data.frames

data <- structure(list(`1.1` = structure(list(id = structure(1, .Dim = c(1L, 
    1L)), Sample = structure("Test1", .Dim = c(1L, 1L)), Add = structure("T", .Dim = c(1L, 
    1L))), .Names = c("id", "Sample", "Add")), `2.1` = structure(list(
     id = structure(5, .Dim = c(1L, 1L)), Sample = structure("Test2", .Dim = c(1L, 
     1L)), Add = structure("A", .Dim = c(1L, 1L))), .Names = c("id", 
    "Sample", "Add")), `3.1` = structure(list(id = structure(7, .Dim = c(1L, 
    1L)), Sample = structure("Test3", .Dim = c(1L, 1L)), Add = structure("D", .Dim = c(1L, 
    1L))), .Names = c("id", "Sample", "Add")), `4.1` = structure(list(
     id = structure(12, .Dim = c(1L, 1L)), Sample = structure("Test4", .Dim = c(1L, 
     1L)), Add = structure("Z", .Dim = c(1L, 1L))), .Names = c("id", 
    "Sample", "Add")), `5.1` = structure(list(id = structure(17, .Dim = c(1L, 
    1L)), Sample = structure("Test12", .Dim = c(1L, 1L)), Add = structure("E", .Dim = c(1L, 
    1L))), .Names = c("id", "Sample", "Add"))), .Names = c("1.1", 
    "2.1", "3.1", "4.1", "5.1"), row.names = c("id", "Sample", "Add" 
    ), class = "data.frame") 

它看起來像這樣:

data 
     1.1 2.1 3.1 4.1 5.1 
id   1  5  7 12  17 
Sample Test1 Test2 Test3 Test4 Test12 
Add  T  A  D  Z  E 

我怎麼可能分裂這個列表按列分成幾個基於ID號碼的數據幀?例如。一個名爲data.ID1的data.frame和一個名爲data.ID5的data.frame和一個名稱爲data.ID 7的data.frame被創建(參見下面的示例)? data.frame的名稱應該與ID號相同。我的列表包含約700種不同的ID和數據...

data.ID1 
id  1 
Sample Test1 
Add  T 

data.ID5 
id  5 
Sample Test2 
Add  A 

data.ID7 
id  7 
Sample Test3 
Add  D 

等等...

+0

是ID值獨特之處? – digEmAll

+0

是的,它們是獨一無二的。 – nebuloso

+0

看着你想要的輸出看起來,你想保持相同的格式(即ID,樣本,添加爲row.names)...我是否正確或你想把它們變成列名? – digEmAll

回答

1

這裏是一個可能的解決方案:

lst <- lapply(1:ncol(data),function(c) return(data[,c,drop=F])) 
names(lst) <- lapply(data,function(col) return(paste0('data.ID',col$id))) 

# here you have data.ID1, data.ID2 etc inside a lst, 
# you can have access to them simply using: lst$data.ID1, lst$data.ID2 etc. 
# but if you REALLY want to add these variables in the environment, 
# continue to the next loop 

for(nm in names(lst)){ 
    assign(nm,lst[[nm]]) 
} 

請注意,最好不使用因爲如上面評論所述,你已經擁有了所有你需要在列表對象「lst」中的內容...但是也許你需要這樣做是爲了一個有效的原因;)

+0

編輯:在data.frame名稱中忘記了「ID」 – digEmAll

0

這裏是一個足夠接近的解決方案,試試

coln <- lapply(data[1,],as.character) 
colnames(data) <- paste(rep("data.TD",ncol(data)),coln,sep="") 
attach(data) 

然後,每當你需要的數據ID調用某列,你這樣做:

data.frame(data.TD7) 

輸出:

id Sample Add 
1 7 Test3 D 

,也可以使用轉它t(data.frame(data.TD7))

0

我想這三條線會解決你的問題:

newdata <- apply(data, 2, function(x) { y = as.data.frame(x=unlist(x)) }) 
newname <- paste("data.ID", unlist(data[1, ]), sep="") 
names(newdata) <- newname 
newdata 

新的數據是包含所需數據的列表框