问题
I'd like to convert a svyrep.design / survey.design object in R into a data frame. I'm aware that this object would be quite large.
library(survey)
data(api) # loads "apiclus2" sample data
dclus2 <- svydesign(id=~dnum+snum, weights=~pw, data=apiclus2)
The above applies weights a data frame, turning it into a survey object.
dclus2 = as.data.frame(dclus2)
Error message:
# Error in as.data.frame.default(dclus2) :
# cannot coerce class ‘c("survey.design2", "survey.design")’ to a data.frame`
I'd like to turn it back into a data frame, with the weights now applied to the object. But as you can see above, this is not possible via "as.data.frame".
回答1:
i think you're looking to do something like this? your example has decimal points in the weights, but you can't have half a record. in the final result x
data.frame, the number of records equals sum of the rounded weights from the original survey data.frame. when you make this conversion, the final data set wouldn't be useful for estimates of uncertainty
library(survey)
data(api)
apiclus2$rounded_weights <- round( apiclus2$pw )
x <- apiclus2[ unlist( mapply( rep , seq( nrow( apiclus2 ) ) , apiclus2$rounded_weights ) ) , ]
sum( apiclus2$rounded_weights ) == nrow( x )
来源:https://stackoverflow.com/questions/55580285/how-to-convert-svyrep-design-to-a-data-frame