我要将2个列表res1
和res2
写入文本文件。
> res1
$`15`
a
g 100
$`10`
a
g 112
$`12`
a
g 70
$`30`
a
g 80
class(res1)
[1] "list"
str(res)
List of 12
$ 1 : num [1, 1] 100
..- attr(*, "dimnames")=List of 2
.. ..$ : chr "g"
.. ..$ : chr "a"
我试过这个:write.matrix(res1,file="myfile.txt",sep="")
但我检查了输出,它是这样的:
100
112
70
80
我想要的输出:
number value
15 100
10 112
12 70
30 80
答案 0 :(得分:3)
试试这个(现在有两个列表):
# an example of a list:
lista <- vector("list", 4)
names(lista) <- c(1, 3, 5, 7)
lista[[1]] <- 30
lista[[2]] <- 50
lista[[3]] <- 20
lista[[4]] <- 33
lista2 <- vector("list", 4)
names(lista2) <- c(1, 3, 5, 7)
lista2[[1]] <- 33
lista2[[2]] <- 5
lista2[[3]] <- 290
lista2[[4]] <- 332
# how to deal with the problem:
macierz <- as.matrix(lista)
macierz <- cbind(as.numeric(rownames(macierz)), macierz)
macierz2 <- as.matrix(lista2)
kolejnosc <- match(rownames(macierz), rownames(macierz2))
cbind(macierz, macierz2[kolejnosc, ]) -> result
colnames(result) <- c("number", "value1", "value2")
write.table(result, "./lista.txt",
row.names=FALSE, col.names=TRUE)
答案 1 :(得分:1)
试试这个,
# sample input
lb <- lapply(1:4, function(x) round(runif(1)*100))
lc <- lapply(1:4, function(x) round(runif(1)*100))
# assuming both lists have the same name
names(lb) <-names(lc) <- c(1:4)
# writing to a file
write.table(x = data.table(name=names(lb),
vb=as.vector(sapply(lb, `[`)),
vc=as.vector(sapply(lc, `[`))),
file = './justCreated.txt',
row.names = F, col.names = T, quote = F)