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

五迷三道 提交于 2019-12-12 03:43:58

问题


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.

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).

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!


回答1:


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

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

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



来源:https://stackoverflow.com/questions/31165141/saving-the-results-of-each-iteration-of-a-for-loop-in-r-as-a-network-object-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!