str and summary don't detect factors

Hello there,
I'm relatively new to R, although I've used it to some extent to perform simple tests.
My issue seems minor, as it doesn't seem to affect what I need to do with my data frames, but it bothers me nonetheless :

When I use str() and summary(), gives me :

summary(data)
Gender Treatment
Length:107 Length:107
Class :character Class :character
Mode :character Mode :character

instead of something like
Gender Treatment
M = x Treatment1 = x1
F = y Treatment2 = y2

and

str(data)
'data.frame': 107 obs. of 6 variables:
Gender : chr "M" "M" "F" "F" ... Treatment : chr "A" "A" "B" "E"

Instead of

Gender : Factor w/ 2 levels "F","M": etc. Treatment : Factor w/ 2 levels "Treatment1", Treatment2... etc.

Any idea why ?
Thanks in advance,
Cheers

Its because they aren't factors, they are chr

Welcome to the community!

Are you reading the dataset from a CSV file? The way you are reading it may affect character/factor.

Up to a very recent update, by default read.csv always used to read character columns as factors. Then it changed and now it's always read as characters. That may explain if your confusion is due to the difference of the results you're getting in the present and past.

If you want to make them as factors while creating the data frame, there are arguments for that, both in read.csv and in other alternative functions.

1 Like

Thank you.

I'm actually not reading from a csv file. I've been trying 2 things :

  • following a tutorial along which the data frame was created from a blank new script, where the "teacher" would get the list with "Factor"
  • using .tab file that my university course provided.
    I'd be interested in those arguments to turn my columns into factor, if you please.
    Cheers

in base R

data$Treatment <- factor(data$Treatment)
1 Like

If you are using the data.frame() function, you can set the argument stringsAsFactors = TRUE

1 Like

Thank you, and thanks @nirgrahamuk as well, both of those did the trick for me.
Have a good one, cheers.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.