ReadSAS in R, filtering and removing columns in this dataset

Hi, I downloaded this CHS 2002 dataset ( Community Health Survey Public Use Data - NYC Health

from SAS to R with the following code.

library(haven)
chs2002_public_1_ <- read_sas("C:/Users/prend/Downloads/chs2002_public (1).sas7bdat",

  • NULL)
    

View(chs2002_public_1_)

This code worked. However, I have been unable to remove columns from this dataset and I have tried various commands. I would like the following variables: mood1, mood2, mood3, mood4, mood5, mood6, sex, cid, newrace, wt1, employment, education, agegroup, incomegroup, uhf42pov, strata, neighpovgroup4_2000.

Ideally, I would like to export this dataset from columns in R to Excel. I would appreciate any of your help as I am a beginner in R.

Thanks!

Welcome to the forum.

You may have to install some packages, particularly the "Hmisc" package but I think this will do what you want. R is case-sensitive and some of your problem may be using mood1 when the actual variable is .MOOD1** and so on.

library(Hmisc)  
library(tidyverse)
library(haven)
library(writexl)


dat1  <- read_sas("chs2002_public.sas7bdat")

## Folowing code uses an Hmisc function to give us a character vector.
xx  <- Cs(MOOD1, MOOD2, MOOD3, MOOD4, MOOD5, MOOD6, sex, cid, newrace, wt1, 
          employment, education, agegroup, incomegroup, uhf42pov, strata, neighpovgroup4_2000)

## Select the desired columns 
dat2  <- dat1[, xx]


write_xlsx(dat2, "nyc.xlsx")

2 Likes

A quick and dirty way to do this is to record the indexes of the variables to be kept, or, if fewer, to be dropped and use those to subset.

colnames(mtcars)
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
#> [11] "carb"
# keep mpg drat wt
# choose all rows [, of mtcars, and mpg drat and wt ]
mtcars[,c(1,5,6)] |> head()
#>                    mpg drat    wt
#> Mazda RX4         21.0 3.90 2.620
#> Mazda RX4 Wag     21.0 3.90 2.875
#> Datsun 710        22.8 3.85 2.320
#> Hornet 4 Drive    21.4 3.08 3.215
#> Hornet Sportabout 18.7 3.15 3.440
#> Valiant           18.1 2.76 3.460
# choose all those EXCEPT
mtcars[,-c(1,5,6)] |> head()
#>                   cyl disp  hp  qsec vs am gear carb
#> Mazda RX4           6  160 110 16.46  0  1    4    4
#> Mazda RX4 Wag       6  160 110 17.02  0  1    4    4
#> Datsun 710          4  108  93 18.61  1  1    4    1
#> Hornet 4 Drive      6  258 110 19.44  1  0    3    1
#> Hornet Sportabout   8  360 175 17.02  0  0    3    2
#> Valiant             6  225 105 20.22  1  0    3    1

Created on 2022-12-24 with reprex v2.0.2

1 Like

Thanks very much! I appreciate your help.

Thanks very much! I appreciate your help.