使用文件名将 R 中 for 循环的每次迭代结果保存为网络对象

Saving the results of each iteration of a for-loop in R as a network object using the filename

我正在尝试 运行 循环遍历许多保存为 .csv 文件的邻接列表,将它们转换为边缘列表和网络对象,并使用文件名保存每一个。

问题是 a) 代码似乎在文件名列表中循环但不产生任何输出 b) 它不会使用文件名保存网络对象(它似乎每次都被覆盖)。

请注意,该代码适用于由 "filename.csv" 标识的单个文件,用于替换 for 循环中的 "f"s。

    l.files <- list.files(patt='.*csv$')
    i <- 0
    for (f in l.files) {

        lines=scan(f,what="character",sep="\n")
        lines=gsub(","," ",lines)
        lines=gsub("[ ]+$","",gsub("[ ]+"," ",lines))
        adjlist=strsplit(lines," ")
        col1=unlist(lapply(adjlist,function(x) rep(x[1],length(x)-1)))
        col2=unlist(lapply(adjlist,"[",-1))
        el=cbind(col1,col2)
        #If second column of el contains 0 then delete
        row_sub = apply(el, 1, function(row) all(row !=0 ))
        #This subset then saved as the new edgelist
        el <- el[row_sub,]
        #Save edgelist using the filename
        el[f] <- el
        summary(el)
        i=i+1
    }

非常感谢任何帮助!

要打开文件,您可以使用system,例如:

l.files <- system('ls *.csv', intern=T)
file.objs <- lapply(l.files, read.table)

那么您应该能够轻松地将 file.objs 中的项目转换为边缘列表。