Re: [R] Accessing a field in a data fram

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Wed, 02 Jul 2008 16:20:21 -0500

on 07/02/2008 02:10 PM R_Learner wrote:
> raw <- read.csv(file=filename, head=TRUE,sep=",")
>
> I've read in a csv file, and I'm looking to access a column whose name is
> held in a string.
>
> For example, I want to access raw$one or raw$two, but this will depending on
> the string. Let's say that the string is decision<-"one". How would I access
> raw$one?
>
> The following doesn't work:
> numbers<-raw$decision
>
> Please help me!
> Thanks!

 > str(iris)
'data.frame': 150 obs. of 5 variables:

  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 
1 1 1 1 1 ...

MyCol <- "Petal.Length"

# Use column indexing
 > iris[, MyCol]
   [1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2 1.5   [17] 1.3 1.4 1.7 1.5 1.7 1.5 1.0 1.7 1.9 1.6 1.6 1.5 1.4 1.6 1.6 1.5 ...

# Use list indexing. A data frame is a list...  > iris[[MyCol]]
   [1] 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 1.5 1.6 1.4 1.1 1.2 1.5   [17] 1.3 1.4 1.7 1.5 1.7 1.5 1.0 1.7 1.9 1.6 1.6 1.5 1.4 1.6 1.6 1.5

# Use subset()
 > subset(iris, select = MyCol)

     Petal.Length
1            1.4
2            1.4
3            1.3
4            1.5
5            1.4

...

See ?"[.data.frame" and ?subset

HTH, Marc Schwartz



R-help_at_r-project.org 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. Received on Wed 02 Jul 2008 - 21:27:04 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 03 Jul 2008 - 16:31:02 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive