List 将列表写入文本文件,保留名称,R
我想将列表写入文本文件,保留名称 这类似于,但我想在每行开头打印出名称:List 将列表写入文本文件,保留名称,R,list,r,List,R,我想将列表写入文本文件,保留名称 这类似于,但我想在每行开头打印出名称: > print(head(mylist,2)) $first [1] 234984 10354 41175 932711 426928 $second [1] 1693237 13462 mylist.txt first 234984 10354 41175 932711 426928 second 1693237 13462 有什么想法吗 非常感谢。cat函数将打印到设备上(默认情况下为控
> print(head(mylist,2))
$first
[1] 234984 10354 41175 932711 426928
$second
[1] 1693237 13462
mylist.txt
first 234984 10354 41175 932711 426928
second 1693237 13462
有什么想法吗
非常感谢。cat函数将打印到设备上(默认情况下为控制台),并且不会添加任何常规注释,但它不能接受列表作为参数,因此所有内容都需要是原子向量。
deparse(substitute())
gambit是恢复传递给函数的列表名称的方法。仅在函数中使用names(x)
无法恢复原始参数的名称
mylist <- list(first =c( 234984, 10354, 41175, 932711, 426928),
second =c(1693237, 13462))
fnlist <- function(x){ z <- deparse(substitute(x))
cat(z, "\n")
nams=names(x)
for (i in seq_along(x) ) cat(nams[i], x[[i]], "\n")}
fnlist(mylist)
mylist
second 234984 10354 41175 932711 426928
first 1693237 13462
mylist您可以通过以下方式获得所需字符串的向量:
sapply(names(mylist),function(x) paste(x,paste(mylist[[x]],collapse=" ")))
first
"first 234984 10354 41175 932711 426928"
second
"second 1693237 13462"
<>你可以用<代码>写< /COD>或<代码>写下 < p>如果你想保存列表以供将来在R中使用,则考虑<代码> r列表包。
付诸表决:
然后,您可以使用以下方法恢复列表,包括名称:
mylist <- list.load("mylist.rds")
mylist@42-
添加到42-的答案中(应该是一个注释,但我无法格式化代码)
我还需要打印列表中向量元素的名称,因此我在cat语句上方添加了这一行,如下所示:
mylist <- list(first =c( a = 234984, b = 10354, c = 41175, d = 932711, e = 426928),
second =c( A = 1693237, B = 13462))
fnlist <- function(x, fil){ z <- deparse(substitute(x))
cat(z, "\n", file=fil)
nams=names(x)
for (i in seq_along(x) ){
cat("", "\t", paste(names(x[[i]]), "\t"), "\n", file=fil, append=TRUE)
cat(nams[i], "\t", x[[i]], "\n", file=fil, append=TRUE) }
}
fnlist(mylist, "test")
很好用!遗憾的是,它需要更多的代码(与没有名字的编写相比)。非常感谢!我也一直不明白为什么cat.list函数不存在。我猜它本质上是低级的,不适合泛化。另外请注意,cat
不能处理带有classlanguage
或call
的对象(可能还有其他对象)。
mylist <- list.load("mylist.rds")
mylist <- list(first =c( a = 234984, b = 10354, c = 41175, d = 932711, e = 426928),
second =c( A = 1693237, B = 13462))
fnlist <- function(x, fil){ z <- deparse(substitute(x))
cat(z, "\n", file=fil)
nams=names(x)
for (i in seq_along(x) ){
cat("", "\t", paste(names(x[[i]]), "\t"), "\n", file=fil, append=TRUE)
cat(nams[i], "\t", x[[i]], "\n", file=fil, append=TRUE) }
}
fnlist(mylist, "test")
mylist
a b c d e
first 234984 10354 41175 932711 426928
A B
second 1693237 13462