hiperhiper
hiperhiper

Reputation: 331

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

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?

Upvotes: 0

Views: 417

Answers (1)

langtang
langtang

Reputation: 24832

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

Upvotes: 1

Related Questions