[R] Removing variables from data frame with a wile card
Bill Dunlap
w||||@mwdun|@p @end|ng |rom gm@||@com
Sat Jan 14 16:36:40 CET 2023
The -grep(pattern,colnames) as a subscript is a bit dangerous. If no
colname matches the pattern then all columns will be omitted (because -0 is
the same as 0, which means no column). !grepl(pattern,colnames) avoids this
problem.
> mydata <- data.frame(A=1:3,B=11:13)
> mydata[, -grep("^yr", colnames(mydata))]
data frame with 0 columns and 3 rows
> mydata[, !grepl("^yr", colnames(mydata))]
A B
1 1 11
2 2 12
3 3 13
-Bill
On Fri, Jan 13, 2023 at 11:07 PM Eric Berger <ericjberger using gmail.com> wrote:
> mydata[, -grep("^yr",colnames(mydata))]
>
> On Sat, Jan 14, 2023 at 8:57 AM Steven T. Yen <styen using ntu.edu.tw> wrote:
>
> > I have a data frame containing variables "yr3",...,"yr28".
> >
> > How do I remove them with a wild card----something similar to "del yr*"
> > in Windows/doc? Thank you.
> >
> > > colnames(mydata)
> > [1] "year" "weight" "confeduc" "confothr" "college"
> > [6] ...
> > [41] "yr3" "yr4" "yr5" "yr6" "yr7"
> > [46] "yr8" "yr9" "yr10" "yr11" "yr12"
> > [51] "yr13" "yr14" "yr15" "yr16" "yr17"
> > [56] "yr18" "yr19" "yr20" "yr21" "yr22"
> > [61] "yr23" "yr24" "yr25" "yr26" "yr27"
> > [66] "yr28"...
> >
> > ______________________________________________
> > R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide
> > http://www.R-project.org/posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
> >
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list