附加到对象列表

时间:2023-01-17 18:15:39

I'm trying to get a list of complex objects (file connections) in R. There is a character vector with file names. I want to open each file with file() and store its connection object somewhere (to be able to close them later). The length of filenames vector is variable. What I'm trying to do is:

我正在尝试获取R中的复杂对象(文件连接)列表。有一个带文件名的字符向量。我想用file()打开每个文件并将其连接对象存储在某处(以便稍后关闭它们)。文件名向量的长度是可变的。我想要做的是:

files <- c("file1", "file2", "file3") #just for example
f <- list()
for (i in 1:length(files))
{
  f<- append(f, file(files[i], open="wt"))
}

Unfortunately f becomes a list of integer and i can't run close() for its elements

不幸的是,f成为整数列表,我不能为其元素运行close()

I need it to stay a list of connection objects:

我需要它来保持连接对象列表:

list(file("fname1"),file("fname2"),file("fname3"))

If you replace append() with list() under the loop it won't convert connections to integers, but that will be a list of list of list etc..

如果在循环下用list()替换append(),它将不会将连接转换为整数,但这将是列表列表等列表。

1 个解决方案

#1


1  

It is not R-style to append items to the list iteratively. More correct to use lapply function which iterates through the given object, apply a user-defined function and returns list. There are three call which should give the same results (not tested).

迭代地将项目附加到列表不是R样式。更正确的是使用lapply函数迭代给定对象,应用用户定义的函数并返回列表。有三个调用应该给出相同的结果(未测试)。

files_connections <- lapply(files, function(f) file(f, open="wt"))
files_connections <- lapply(files, file, "wt")
files_connections <- lapply(files, file, open="wt")

#1


1  

It is not R-style to append items to the list iteratively. More correct to use lapply function which iterates through the given object, apply a user-defined function and returns list. There are three call which should give the same results (not tested).

迭代地将项目附加到列表不是R样式。更正确的是使用lapply函数迭代给定对象,应用用户定义的函数并返回列表。有三个调用应该给出相同的结果(未测试)。

files_connections <- lapply(files, function(f) file(f, open="wt"))
files_connections <- lapply(files, file, "wt")
files_connections <- lapply(files, file, open="wt")