Q:

Loop to sample random points within several polygons in R

I have a shapefile with 6 polygons, each one with a specific id.
I want to create random points within these polygons, but with different sample size (each id has a specific value).
The file with the polygons has the following structure:
> HR95_all
Object of class "SpatialPolygonsDataFrame" (package sp):

Number of SpatialPolygons:  6

Variables measured:
   id      area
0  40 257879080
01 41  53136845
02 42  64198336
03 43 186475935
04 44  27405855
05 45  53485801

And the data.frame with the number of points per id is a simple data.frame:
> AV_locs
   id  num
40 40 1010
41 41 1222
42 42  493
43 43 1111
44 44  369
45 45  598

I would like to create a loop that could do this automatically, and I've tried this:
for (i in 1:length(unique(HR95_all$id))) {
             id <- unique(HR95_all$id)[i]
             Rnd <- spsample(HR95_all[[id]], AV_locs[which(AV_locs$id==id), "num"] , "random")
             writeOGR(Rnd,dsn=getwd(), layer=paste0("Rnd_", id), driver = "ESRI Shapefile",overwrite_layer=TRUE)
     }

But I obtain the following error:
Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘spsample’ for signature ‘"factor"’

I've tried other options, like including n = AV_locs[which(AV_locs$id==id), "num"] (following the help page), but the error persists. 
Any idea on how to overcome this? 
----- UPDATE -----
I've tried a different loop, by subsetting the HR95_all before applying the spsample():
for (i in (unique(HR95_all$id))) {
        HR <- HR95_all[HR95_all$id==i,]
        Rnd_locs <- spsample(HR, n = AV_locs[which(AV_locs$id==i), "num"], "random")
        writeOGR(Rnd_locs,dsn=getwd(), layer=paste0("Random_", i), driver = "ESRI Shapefile",overwrite_layer=TRUE)
}

The previous error is gone but a new one showed up:
Error in writeOGR(Rnd_locs, dsn = getwd(), layer = paste0("Random_", i),  : 
  obj must be a SpatialPointsDataFrame, SpatialLinesDataFrame or
    SpatialPolygonsDataFrame

I've tried to add a as(Rnd_locs, "SpatialPointsDataFrame") before, but it still doesn't work; I recieve this error: 
Error in writeOGR(Rnd_locs, dsn = getwd(), layer = paste0("Random_", i),  : 
  NA NULL unknown data type

Any thoughts?

A:

The issue was solved by simply converting the object obtained from spsample() into a SpatialPointsDataFrame (following Convert SpatialPoints to SpatialPointsDataFrame); spsample() returned an object from a SpatialPoint class, which is not supported by writeORG().
My final loop was:
for (i in (unique(HR95_all$id))) {
        HR <- HR95_all[HR95_all$id==i,]
        Rnd_locs <- spsample(HR, n = AV_locs[which(AV_locs$id==i), "num"] , "random")
        Rnd_locs_SP <- SpatialPointsDataFrame(Rnd_locs, data.frame(ID=1:length(Rnd_locs)))
        writeOGR(Rnd_locs_SP,dsn=getwd(), layer=paste0("Random_", i), driver = "ESRI Shapefile",overwrite_layer=TRUE)
}

