1
votes

I have survey data with a weighting variable called weight that I want to use on my dataset. The survey package unfortunately doesn't work as I was thinking. What I finally need is to

  1. plot a (bar)chart (with percentage of the distribution on y-axis) that considers the weighting but keeps the levels of the factor (on the x-axis).
  2. somehow export the weighted dataset to SPSS.

Is there a way this could work? A solution even with the survey package would be ok as I have no objectives but still couldn't get it to work.

I know there are some posts regarding weighting issues, but I couldn't find a fitting solution to my issue. Thanks for your help.

# create data
surveydata <- as.data.frame(replicate(1,sample(0:1,1000,rep=TRUE)))

# change values of columns
surveydata$V1 <- (replicate(1,sample(c(0.5,1,1.5),1000,rep=TRUE)))
surveydata$V2 <- as.factor(sample(3, size = nrow(surveydata), replace = TRUE))
          levels(surveydata$V2)[levels(surveydata$V2)=="1"] <- "a"
          levels(surveydata$V2)[levels(surveydata$V2)=="2"] <- "b"
          levels(surveydata$V2)[levels(surveydata$V2)=="3"] <- "c"

# rename columns
colnames(surveydata)[1] <- "weight"
colnames(surveydata)[2] <- "variable"
1

1 Answers

3
votes

With proportions rather than percentages

> library(survey)
> des<-svydesign(id=~1, weights=~weight,data=surveydata)
> barplot(svymean(~variable,des))

a barplot

With percentages the easiest way is probably to use svytable(), which has an argument for scaling the totals: the code below shows totals, proportions, and percentages

> svytable(~variable,des)
variable
    a     b     c 
320.5 365.5 331.5 
> svytable(~variable,des,Ntotal=1)
variable
        a         b         c 
0.3149877 0.3592138 0.3257985 
> svytable(~variable,des,Ntotal=100)
variable
       a        b        c 
31.49877 35.92138 32.57985 

So

barplot(svytable(~variable,des,Ntotal=100),col="orange",ylab="%")

barplot with percentages

To transfer the data to SPSS, I would use write.foreign(), which produces a plain-text data file and an SPSS code file to read it in.