简体   繁体   中英

How to load CSV as factor in R

I have a file called metadata.csv that I want to load into R and convert to a factor. I begin with:

metadata <- read.csv(file="metadata.csv", header=T, stringsAsFactors=T)

And this loads the CSV just fine. I've printed out metadata here:

> metadata
                   Filename  Genre   Date Gender
1           Austen_Emma.txt Social  Early Female
2           Bronte_Eyre.txt Social Middle Female
3  Dickens_Expectations.txt Social   Late   Male
4            Eliot_Mill.txt Social   Late Female
5            Lewis_Monk.txt Gothic  Early   Male
6     Radcliffe_Italian.txt Gothic  Early Female
7  Shelley_Frankenstein.txt Gothic Middle Female
8        Stoker_Dracula.txt Gothic   Late   Male
9      Thackeray_Vanity.txt Social Middle   Male
10       Trollope_Vicar.txt Social Middle   Male

Now I want to convert it to a factor:

as.factor(metadata)

This gives me the following error:

Error in sort.list(y) : 'x' must be atomic for 'sort.list'
Have you called 'sort' on a list?

metadata is a dataframe which is a special type of list made up of vectors of equal length. You can only use as.factor() on vectors. Therefore you must class as.factor() on each vector in the dataframe. This can be done using the lapply function:

metadata <- data.frame(lapply(metadata, factor))

This will convert each column to a factor (check this by class(metadata[, 1]) ). The overall structure of metadata will still be a dataframe.

read.csv puts data into a data.frame

You cannot convert a data.frame into a factor . That's very basic R stuff.

It's like you're trying to change of a bunch of .doc files into PDFs by converting your computer into a PDF. It just doesn't make sense.

The error is asking "Have you called sort on a list?" Yes, you have. as.factor calls sort , and your data.frame is a list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM