Mainland
Mainland

Reputation: 4584

Error in svytotal() : could not find function "svytotal"

I am close to running the script successfully and I got this error in the final script. I am running it on the Rstudio cloud.I computed it by referring PDF: 2020 microdata file to compute estimates and standard errors (RSEs).Page 6,7 in the webpage survey link Here is my complete script:

# Ref: file:///C:/Users/MMatam/OneDrive%20-%20University%20of%20Central%20Florida/Projects/20230123_US_EIA_DataAnalysis/Residential_BatteryPV_ElectricVehicle_MM/ResidentialEnergyConsumptionSurvey_RECS/microdata-guide.pdf
install.packages("survey")
library(survey)
# Ref: https://stackoverflow.com/questions/54621706/error-in-librarydplyr-there-is-no-package-called-dplyr
install.packages('dplyr')
library(dplyr)
# Import the CSV file from local machine
# Ref: https://community.rstudio.com/t/how-can-i-upload-csv-or-excel-files-existing-in-computer-to-rstudio-cloud/23621
# To import the csv again into this space, right click on the file name and click import dataset
recs2020 <- read_csv(file="recs2020_public_v1.csv")
# Read the 
recs2020$NG_MAINSPACEHEAT <- ifelse(recs2020$FUELHEAT == 1, 1, 0)
# 
repweights<-select(recs2020,NWEIGHT1:NWEIGHT60)
#
RECS <- svrepdesign(data = recs2020,
                    weight = ~NWEIGHT,
                    repweights = repweights,
                    type = "JK1",
                    combined.weights = TRUE,
                    scale = (ncol(repweights)-1)/ncol(repweights),
                    mse = TRUE)
#
NG_MAINSPACEHEAT<-as.data.frame(svytotal(~NG_MAINSPACEHEAT,RECS))

Present output:

Error in svytotal(~NG_MAINSPACEHEAT, RECS) : 
  could not find function "svytotal"

Upvotes: 0

Views: 82

Answers (1)

Anthony Damico
Anthony Damico

Reputation: 6114

library(haven)
library(survey)

sas_url <-
    "https://www.eia.gov/consumption/residential/data/2020/sas/recs2020_public_v1.zip"

tf <- tempfile()

download.file( sas_url , tf , mode = 'wb' )

recs_tbl <- read_sas( tf )

recs_df <- data.frame( recs_tbl )

names( recs_df ) <- tolower( names( recs_df ) )

recs_design <-
    svrepdesign(
        data = recs_df ,
        weight = ~ nweight ,
        repweights = 'nweight[1-9]+' ,
        type = 'JK1' ,
        combined.weights = TRUE ,
        scale = 59 / 60 ,
        mse = TRUE
    )

svytotal( ~ as.numeric( fuelheat == 1 ) , recs_design )
                             # total     SE
# as.numeric(fuelheat == 1) 56245389 545591

Upvotes: 1

Related Questions