[R] Stuck with levels while reassigning dataframe colnames?

David Winsemius dwinsemius at comcast.net
Thu Feb 2 04:53:08 CET 2012


On Feb 1, 2012, at 10:21 PM, jjap wrote:

> Dear users,
> I am importing a csv file whose first row is a single value that I  
> need to
> capture in a variable.
>  infile<-file.choose()
>  in<-read.csv( infile, header=FALSE)
>  single.value<-as.character(in[1,1])  # fine
>
> Now I need to take rows 3 and on as the data
>  df<-in[3:dim(in)[1],]
>
> But row 2 contains what I want as header of df.
>  colnames(df)<-in[2,]

Try

   names(df) <- as.character( colnames(df)<-in[2,] )


> This gets a series of numbers (characters) "2" "5" "3" "11" instead  
> of:
>   "CatA" "Time" etc.
> I suspect this has something to do with levels, but I cannot seem to  
> find a
> way to get the proper names.

You should do more reading on the construction of levels. Those column  
names are now "polluting" your factor levels. It would have been  
cleaner to read the first line of the file and then used read.table()  
with sep="," skip = 1,  and header=TRUE. You can try to fix _your_  
polluted factor problem with:

  df <- as.data.frame( lapply( df, factor))

All of the above untested in the absence of a reproducible example.


-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list