删除 R 中的多列

Removing multiple columns in R

我有一个包含大约 2,384 个变量的数据集,但只需要使用其中的大约 39 个。我试图将我正在使用的列删除到另一个数据集中,但我不断收到未定义的列选择错误消息。下面是我写的代码:

BR <- BR[ c("id","today_m0","miscarriedwk","p1_status","p2_status","p_status", "p3_status","preg_bl","preg_m6","preg_m12","preg_m18","secedu","married","numchild","numpregnancies","nummiscarriages","numdeliveries","pHIV_bsln","chart_cd4_m0","j8_m0","partnernowsHIV_m0","partnertakesHIV_m0","depression_m0" ,"meanhivstigma_m0","meanpersonalstigma_m0","female_m0","CommstigmaFinal_m0","j12r_m0","PMTCT","ANC","j10_m0","age_m0","intention1year")]

dplyr 包是清理数据的好工具:

library(dplyr)
select(BR, id, today_m0, miscarriedwk, p1_status, # etc

使用这种方法的好处在于错误消息会告诉您哪些列名是错误的:

> select(BR, junk)
Error in eval(expr, envir, enclos) : object 'junk' not found