[R] correct way to subset a vector

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Jul 9 17:54:53 CEST 2009


Hi,

On Jul 9, 2009, at 11:40 AM, Juliet Hannah wrote:

> Hi,
>
> #make example data
> dat <- data.frame(matrix(rnorm(15),ncol=5))
> colnames(dat) <- c("ab","cd","ef","gh","ij")
>
> If I want to get a subset of the data for the middle 3 columns, and I
> know the names of the start column and the end column, I can do this:
>
> mysub <- subset(dat,select=c(cd:gh))
>
> If I wanted to do this just on the column names, without subsetting
> the data, how could I do this?
>
> mynames <- colnames(dat);
>
> #mynames
> #[1] "ab" "cd" "ef" "gh" "ij"
>
> Is there an easy way to create the vector c("cd","ef","gh") as I did
> above using something similar to cd:gh?

How about just taking your mynames vector? eg:

R> mynames[2:4]
[1] "cd" "ef" "gh"

R> dat[, mynames[2:4]]
           cd         ef          gh
1  1.7745386  1.0958930 -0.07213304
2  0.7480372 -0.1364458 -0.62848211
3 -0.5477843  1.5811382 -0.74404103

-steve

--
Steve Lianoglou
Graduate Student: Physiology, Biophysics and Systems Biology
Weill Medical College of Cornell University

Contact Info: http://cbio.mskcc.org/~lianos




More information about the R-help mailing list