Use for loop and rbind to repeat multiple files

I have a small R script of 14 functions and you want to run it for 81 files. Although I read a few stack overflow messages that address similar issues, I still have problems with this. I use the loop forand rbind.

All functions in the { }work cycle. I tested them without a loop for, and I get the data vector that I need. But when I run the loop for, I only get output for the last file in the folder. I'm not sure what is going on.

Does the loop work correctly for(it iterates through files) and just overwrites previous runs? If the loop forworks, I assume I have a problem with mine rbind. Or, fordoes the loop only work with the last file in list.files()?

In the end, I want to get a matrix (or table) with the results of 14 functions for each of the 81 files.

Here is the code:

res=(1:14)
for(i in list.files())
{ 
  nd = read.csv(i, header= TRUE, row.names =1, check.names = FALSE)
  mx = as.matrix(nd)

  res[1]=basename(i) 
  res[2]=-99  #this is just a place holder
  res[3]=gden(mx) 
  res[4]=centralization(mx,degree)

  deg = degree(mx, gmode="graph", diag=FALSE, rescale=FALSE)
  res[5]=mean(deg)
  res[6]=sd(deg)
  res[7]=max(deg)
  res[8]=min(deg)

  Ndeg = degree(mx, gmode="graph", diag=FALSE, rescale=TRUE)*1000
  res[9]=mean(Ndeg)
  res[10]=sd(Ndeg)
  res[11]=max(Ndeg)
  res[12]=min(Ndeg)

  iso = isolates(mx, diag=FALSE)
  res[13]=length(iso)

  res[14]=nrow(mx)
}
results=rbind(res)
results  
+3
source share
3 answers

Make your feature set together a new feature sapplyfor each element list.files():

out <- sapply(list.files(), function(i){ 
  nd = read.csv(i, header= TRUE, row.names =1, check.names = FALSE)
  mx = as.matrix(nd)

  res = numeric(14)
  res[1]=basename(i) 
  res[2]=-99  #this is just a place holder
  res[3]=gden(mx) 
  res[4]=centralization(mx,degree)

  deg = degree(mx, gmode="graph", diag=FALSE, rescale=FALSE)
  res[5]=mean(deg)
  res[6]=sd(deg)
  res[7]=max(deg)
  res[8]=min(deg)

  Ndeg = degree(mx, gmode="graph", diag=FALSE, rescale=TRUE)*1000
  res[9]=mean(Ndeg)
  res[10]=sd(Ndeg)
  res[11]=max(Ndeg)
  res[12]=min(Ndeg)

  iso = isolates(mx, diag=FALSE)
  res[13]=length(iso)

  res[14]=nrow(mx)
  return(res)
}
out
+2
source

you should have rbind (res) inside the loop, something like this results = rbind (res), but that is not enough. something like results = rbind (results, res)

, .. sapply ..

-1

, - . :)

res=(1:14)
summary=(1:14)
for(i in list.files())
{ 
  ....code as above.....

  summary=rbind(summary, res)  
}

summary

# then to put into a .csv
write.csv(summary, "nameoffile.csv")
-2
source

All Articles