使用文件名将R中for循环的每次迭代结果保存为网络对象 [英] Saving the results of each iteration of a for-loop in R as a network object using the filename

查看:315
本文介绍了使用文件名将R中for循环的每次迭代结果保存为网络对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to run a loop to iterate through a number of adjacency lists saved as .csv files, convert them to edge lists, and network objects, and save each of these using the filename.

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

The problem is a) the code appears to cycle through the list of filenames but not produce any output b) it won't save the network objects using the filenames (it appears to overwrite each time).

请注意,该代码对于用"filename.csv"标识的单个文件代替for循环中的"f"可以正常工作.

Note that the code works fine for an individual file identified by "filename.csv" in replacement of the "f"s in the for-loop.

    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
    }

任何帮助将不胜感激!

Any help would be very much appreciated!

推荐答案

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

To open the files, you can use system, e.g.:

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

然后,您应该可以轻松地将file.objs中的项目转换为边缘列表.

Then you should be able to easily convert the items in file.objs to edgelists.

这篇关于使用文件名将R中for循环的每次迭代结果保存为网络对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆