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,] 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. Any help or hint is appreciated. -- View this message in context: http://r.789695.n4.nabble.com/Stuck-with-levels-while-reassigning-dataframe-colnames-tp4350435p4350435.html Sent from the R help mailing list archive at Nabble.com.
David Winsemius
2012-Feb-02 03:53 UTC
[R] Stuck with levels while reassigning dataframe colnames?
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
Thanks for the advice, df<-read.table(infile, sep="," skip = 1, header=TRUE) is indeed much cleaner from the outset (and was my usual way to it). I was unaware that readLines(infile, n=1) could get me the first line without reading the whole file again. But I do need to get my head around these levels... ---Jean Plamondon -- View this message in context: http://r.789695.n4.nabble.com/Stuck-with-levels-while-reassigning-dataframe-colnames-tp4350435p4351528.html Sent from the R help mailing list archive at Nabble.com.