[R] foor loop - undefined columns selected error

Peter Ehlers ehlers at ucalgary.ca
Wed Nov 18 16:57:41 CET 2009



Michela Leonardi wrote:
> Dear R-Help Members,
> 
> I am trying to read and analyse a set of 100 csv files.
> I need work only on some columns in each of those, so I decided to use
> a for loop, isolate the
> column in each file to work on, but then an error mesage appear:
> "undefined columns selected"
> 
> Here is my code:
> 
> setwd("F:/Data/")
> a<-list.files()
> for (x in a) {
>   u<-read.csv(x, header=T, sep=",", check.names=FALSE)
> #it give me the same problem using read.table
>   h<-u[,2]
> }
> 
> Error in `[.data.frame`(u, , 2) : undefined columns selected
> 
> It does not give me any problem selecting ane entire row (e.g. u[2,])
> or a single value (e.g. [5,2])
> If I try to select a column after the for loop I does not show any
> problem, e.g.:
> 
> a<-list.files()
> for (x in a) {
>   u<-read.csv(x, header=T, sep=",", check.names=FALSE)
> }
>   h<-u[,2]
> 
> I would appreciate any suggestion or pointer to solve the problem or
> to do the same thing in a different way.
> 
> Thanks for your consideration
> 

Michela,

What are your loops supposed to accomplish? They
just give you the last file in 'a'.
When you get the error, that indicates that at least
one of your files has only one column.
You don't get the error when you take h<-u[,2] out
of the loop because the last file in 'a' does happen
to have 2 or more columns.
You need to rethink the loop with regard to what
you will do with 'h'. And you need to check what's
in those files.

  -Peter Ehlers

> --
> Michela Leonardi
> 
> ______________________________________________
> 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.
> 
>



More information about the R-help mailing list