2015-07-21 61 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 

新的数据是包含所需数据的列表框