Home > Mobile >  Create an empty data.frame and fill each row in R after looping
Create an empty data.frame and fill each row in R after looping

Time:09-01

I want to fill a data.frame by rows. My results are vectors such as

spp = c("sp1", "sp2", "sp3")
roc = c(0.74, 0.75, 0.76)
prc = c(0.45, 0.46, 0.47)

I'm posting the results as vectors because they came from a prior loop, so I'm trying to fill by loop.

What I'm trying to do returns the ''replacement has 0 rows'' error.

An ideal result would look like

data.frame(spp = c("sp1", "sp2", "sp3),
           roc = c("0.74, 0.75, 0.76),
           pcr = c(0.45, 0.46, 0.47))

So that each row is filled iteratively, one by one.

How can I proceed?

CodePudding user response:

One approach is to generate the structure of your data.frame prior to looping, and then within each iteration of the loop over species (say sp) that produces the single values for roc (say, roc_i) and prc (say, prc_i), add them to the data.frame:

result=structure(list(spp = character(), roc=float(),prc=float()),class = "data.frame")

for(sp %in% unique(species)) {
  #code that produces roc_i, prc_i for sp
  ...
  # add row to result
  result = rbind(result, data.frame(spp=sp,roc=roc_i, prc=prc_i)
}
  • Related