[R] Thanks!
R_Learner
sschiang8 at gmail.com
Thu Jul 3 17:35:30 CEST 2008
Thanks guys!
I think [[ seems to be the easier way, but I also spent an hour (while my
post was pending approval) to find that the following also works:
temp<- eval(parse(text=paste("data$column_title"")))
Marc Schwartz wrote:
>
> 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.
>
>
--
View this message in context: http://www.nabble.com/Accessing-a-field-in-a-data-fram-tp18244661p18260722.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list