[R] error when extracting from a data frame

David Winsemius dwinsemius at comcast.net
Tue Jan 17 23:44:16 CET 2012


On Jan 17, 2012, at 4:56 PM, Jean V Adams wrote:

> Read the help file on how to extract from a data frame:
> ?"[.data.frame"
>
> Then, try adding a comma inside the brackets.
> data.station1 <- data[data$Station==1, ]
> Before the comma, the data$Station==1 identifies what rows to select.
> After the comma, the lack of specification indicates that all columns
> should be selected.
>

And if you want to avoid getting all the rows where data$Station are  
NA,  then use either of these alternatives resulting in what I expect  
and generally want to see as a result:

  data.station1 <- subset( data, Station==1 )
  data.station1 <- data[ which(data$Station==1) , ]

-- 
David.
> Jean
>
>
> Suzanne.mertens wrote on 01/17/2012 03:17:41 PM:
>
>> (As a noob to R, this is my first posting - yes yes, groans all
> around...)
>>
>> I'm trying to extract certain rows from a data frame. I used the
>> following to import data from a CSV txt file.
>>
>>   data <- read.table(file="data.txt", header=TRUE)
>>
>> when I do this, my attempt to extract the data rows only from where
>> the Station value equals 1?
>>
>>   data.station1 <- data[data$Station == 1]
>>
>> ...is giving me the following error message:
>>
>>   Error in `[.data.frame`(data, data
>> $Station == 1) :
>>     undefined columns selected
>>
>>
>> Bah.
>> If I use names(data) I can see "Station" as a column name.
>> And if I use str(data), the variable "Station" is coming up as
>> integers including the value 1.
>> And if I use data$Station, I see all station values, including the  
>> 1s.
>> And if I use data[,"Station"] I do see all the Station values
>> And if I instead treat the Station values as characters, by using
>> "1", I still get the "undefined" error.
>>
>> Could someone please correct me on my syntax? Or advise if perhaps I
>> imported the data the wrong way? I'm working out of "A Beginner's
>> Guide to R" and also looked through the R manual, and even tried
>> this from  Google search:
>>
>>   data.station1 <- data,("Station" == 1) ]
>>
>> But that gave me an unwanted output:
>>   data frame with 0 columns and 789 rows
>>
>> Almost, but not quite. Please help?
>>
>>
>> Thank you,
>>
>>
>>
>> - Suzanne
>> ..........................................
>> suzanne.mertens at gmail.com
>> 404-337-1533
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list