我有一个字符向量列表,我想将列表写入包含所有字符向量的单个文件。以下是我需要的一个例子:
>str(mylist)
List of 19
$ geneset1 : chr [1:140] "ASGR2" "ATXN7L3" "BCL6B" "C6orf211" ...
$ geneset2 : chr [1:174] "CKS1B" "CREBL2" "CTNNB1" "CTTN" ...
$ geneset3 : chr [1:346] "AGTR1" "C6" "C6orf211" "CCNK" ...
$ geneset4 : chr [1:259] "ASGR2" "ATF7IP" "ATXN7L3" "CKS1B" ...
我想要的输出是这样的文件:
#myfile
>geneset1
ASGR2 ATXN7L3 BCL6B C6orf211
>geneset2
ASGR2 ATXN7L3 BCL6B C6orf211
>geneset3
AGTR1 C6 C6orf211 CCNK
我的方法是:
writeLines(unlist(lapply(mylist, FUN=function(x)paste(x, collapse=" "))), con="test.txt")
但是,我不知道如何添加“>”在行的开头
由于
答案 0 :(得分:4)
你可以使用for looop:
out=stdout()
X <- list(geneset1= c("ASGR2","ATXN7L3","BCL6B","C6orf211"),
geneset2= c("CKS1B","CREBL2","CTNNB1","CTTN"),
geneset3= c("AGTR1","C6","C6orf211","CCNK" ),
geneset4= c("ASGR2","ATF7IP","ATXN7L3","CKS1B" ) )
for(i in names(X)) {
cat(">", i, "\n", file=out)
cat(X[[i]], "\n", file=out)
}
答案 1 :(得分:2)
足够接近,
writeLines(sapply(names(X),function(x) paste(paste0(">",x,"\n"),paste(X[[x]],collapse=" "))), con="test.txt")
答案 2 :(得分:1)
一种方法是使用use.names
中的unlist
参数,然后使用paste
或paste0
附加名称:
mylist <- list(geneset1 = c("ASGR2","ATXN7L3","BCL6B","C6orf211"),
geneset2 = c("CKS1B","CREBL2","CTNNB1","CTTN"),
geneset3 = c("AGTR1","C6","C6orf211","CCNK" ),
geneset4 = c("ASGR2","ATF7IP","ATXN7L3","CKS1B" ) )
unlisted <- unlist(lapply(mylist, function(x) { paste(x, collapse = " ") }), use.names = TRUE)
names(unlisted) <- paste0(">", names(unlisted))
names(unlisted)
write.table(unlisted, file = "test.txt", quote = FALSE,
sep = "\n", col.names = FALSE)
答案 3 :(得分:1)
将Neal的解决方案变成一个功能:
writeGeneSets <- function(genesets, filename) {
if (missing(filename)) {
conn <- stdout()
} else {
conn <- file(filename, open="w")
on.exit( close(conn) )
}
for (name in names(genesets)) {
writeLines(paste(">", name), conn)
writeLines(paste(genesets[[name]], collapse=" "), conn)
}
}
......我们可以这样试试:
genesets <- list(geneset1= c("ASGR2","ATXN7L3","BCL6B","C6orf211"),
geneset2= c("CKS1B","CREBL2","CTNNB1","CTTN"),
geneset3= c("AGTR1","C6","C6orf211","CCNK" ),
geneset4= c("ASGR2","ATF7IP","ATXN7L3","CKS1B" ) )
writeGeneSets(genesets)
writeGeneSets(genesets, "test1.txt")