« Return to Thread: correct way to subset a vector

Re: correct way to subset a vector

by Steve Lianoglou-6 :: Rate this Message:

Reply to Author | View in Thread

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

______________________________________________
R-help@... mailing list
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.

 « Return to Thread: correct way to subset a vector