Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind rows of svymean output?

In order to apply weights etc. on survey data I am working with the survey package. There included is a wonderful function svymean() which gives me neat pairs of mean and standard errors. I now have several of these pairs and want them combine with rbind() into a data.frame.

library(survey)
data(fpc)

fpc.w1 <- with(fpc, svydesign(ids = ~0, weights = weight, data = fpc))
fpc.w2 <- with(fpc, svydesign(ids = stratid, weights = weight, data = fpc))

(msd.1 <- svymean(fpc$x, fpc.w1))
#        mean     SE
# [1,] 5.4481 0.7237

(msd.2 <- svymean(fpc$x, fpc.w2))
#        mean     SE
# [1,] 5.4481 0.5465

rbind(msd.1, msd.2)
#           [,1]
# msd.1 5.448148
# msd.2 5.448148

As one can see, the SE is missing. Examining the object yields following:

class(msd.1)
# [1] "svystat"

str(msd.1)
# Class 'svystat'  atomic [1:1] 5.45
#   ..- attr(*, "var")= num [1, 1] 0.524
#   .. ..- attr(*, "dimnames")=List of 2
#   .. .. ..$ : NULL
#   .. .. ..$ : NULL
#   ..- attr(*, "statistic")= chr "mean"

So I made some guesswork.

msd.1$mean
# Error in msd.1$mean : $ operator is invalid for atomic vectors

msd.1$SE
# Error in msd.1$SE : $ operator is invalid for atomic vectors

msd.1[2]
# [1] NA

msd.1[1, 2]
# Error in msd.1[1, 2] : incorrect number of dimensions

Included in the package is a function called SE() which yields:

SE(msd.1)
#          [,1]
# [1,] 0.723725

Ok. By this I finally could accomplish a solution to bind these rows:

t(data.frame(msd.1=c(msd.1, SE(msd.1)),
             msd.2=c(msd.2, SE(msd.2)),
             row.names = c("mean", "SD")))
#           mean        SD
# msd.1 5.448148 0.7237250
# msd.2 5.448148 0.5465021

Do I actually have to take this pain with the package to bind rows, or am I missing something?

like image 915
jay.sf Avatar asked Sep 14 '25 02:09

jay.sf


1 Answers

You can just coerce the svymean output to a data frame, then rbind them together.

do.call(rbind, lapply(list(msd.1, msd.2), as.data.frame))

      mean        SE
1 5.448148 0.7237250
2 5.448148 0.5465021

If you want to add names, you have to name the items in the list and then set USE.NAMES = TRUE in lapply

do.call(rbind, lapply(list("msd.1"= msd.1, "msd.2" = msd.2), as.data.frame, USE.NAMES = TRUE))

          mean        SE
msd.1 5.448148 0.7237250
msd.2 5.448148 0.5465021
like image 165
Jake Kaupp Avatar answered Sep 16 '25 17:09

Jake Kaupp