简体   繁体   中英

Read data frame of factors (in R)

I am a novice to R. To use in a package I need a "data frame of factors".

I have a text file of form:

A B C ...
1 3 2
2 2 3
3 1 1
2 2 1
3 1 2

So each column represents a variable that can be 1, 2 or 3. Please suggest a command that allow me to get a Data Frame of factors from such a text file (just reading the file as a matrix won't do, I am required to have real 'factors').

Thanks in advance.

It seems that setting the colClasses parameter of read.table to:

colClasses = c(rep("factor",26)) 

would do the job I require.

a <- read.table(textConnection("A B C
1 3 2
2 2 3
3 1 1
2 2 1
3 1 2"), header=T, colClasses="factor")

str(a)
## 'data.frame':    5 obs. of  3 variables:
##  $ A: Factor w/ 3 levels "1","2","3": 1 2 3 2 3
##  $ B: Factor w/ 3 levels "1","2","3": 3 2 1 2 1
##  $ C: Factor w/ 3 levels "1","2","3": 2 3 1 1 2

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