One of the issues that appeared during our first meeting was:
What is this thing called factors?
They appeared when we loaded temperature data using read.table(). Here is a small explanation:
In R, factors are a way to represent categorical values. Since in the temperature dataset there was the string “—” indicating missing values, the read.table() function did not recognize the data as numerical values, but it assigned categories to them instead. In the book “R in a nutshell” by J. Adler, factors are explained as “an ordered collection of items” and further “The different values that the factor can take are called levels”.
Assume the participants of a survey answered (“male”,”male”,”female”,”other”,”male”), when asked about their sex. There is no inherent ordering in these levels. These answers can simply be represented in R as
> answers <- factor(c("male","male","female","other","male"))
If you query the variable “answers”, R will tell you
> answers [1] male male female other male Levels: female male other
If you want to have the answers in character format, you simply do
> as.character( answers ) [1] "male" "male" "female" "other" "male"
Now, sometimes there is an inherent ordering in the possible answers, such as when participants are asked about the climate in their country and the answers are (“hot”,”moderate”,”hot”,”cold”,”hot”). These answers can be represented like this
> answers <-factor( c("hot","moderate","hot","cold","hot"),
levels=c("cold","moderate","hot"), ordered=T)
Here the levels-attribute tells R the inherent (increasing) ordering of the levels. If we query for “answers”, we get
> answers [1] hot moderate hot cold hot Levels: cold < moderate < hot
Notice the ordering is indicated by “<“, as opposed to the unordered answers above. Converting to character works as above. Converting to numeric values works by
> as.numeric( answers ) [1] 3 2 3 1 3
If, as in the temperature data, the variable contains factors, but this is unwanted, there are several ways around this. Say the data that was read from the file appears as factors of the form (“2.1″,”2.1″,”—“,”2.5″,”3.0”)
> temp <- factor(c("2.1","2.1","---","2.5","3.0"))
> temp
[1] 2.1 2.1 --- 2.5 3.0
Levels: --- 2.1 2.5 3.0
but you would like them as numerical values. Simply issueing as.numeric(temp) does not return the actual temperature values but the integers that R inherently assigned to the levels:
> as.numeric(temp) [1] 2 2 1 3 4
A quick and dirty way to get the actual temperature values and have the “—” appear as NA (“not available”) would be to convert to character first and then to numeric:
> as.numeric(as.character(temp)) [1] 2.1 2.1 NA 2.5 3.0 Warning message: NAs introduced by coercion
The warning can be avoided by enclosing the above call inside the function “suppressWarnings()”. A more elegant way to transform the contents of the file to numerics would be to use the options of the read.table() function. But this is another topic.