Principal Components Analysis:Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric

Viewed 74532

I'm trying to execute a Principal Components Analysis, but I'm getting the error: Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric

I know all the columns have to be numeric, but how to handle when you have character objects in the data set? E.g:

data(birth.death.rates.1966)
data2 <- birth.death.rates.1966
princ <- prcomp(data2)
  • data2 example of data below:

enter image description here

Should I add a new column referring the country name to a numeric code? If yes, how to do this in R?

3 Answers

In R, adding the factor method to a character set of data, does not make it numeric. Indeed it is to make our machine learning model a mathematical model but it is not numeric data.

Example: If you have a list of names and then they are being encoded numerically then it may happen that a certain name may have a higher numerical value which will give it a different definition depending on our model.
Which should not be the case as names(text data which is just for labeling a specific set) generally should not define the way a model should work.

Also if you try working with this data assuming it to be numeric, you may get the following error:

Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric

I have defined why you may get this error above

To overcome this problem

training_set[,2:3] = scale(training_set)
test_set[,2:3] = scale(test_set)

In the following image, columns 1 and 4 have encoded data and cannot be treated as a numerical model Columns 2 and 3 have been originally containing numerical data so we can run our model only on that part of the data. The above code just shows how to select the data it includes all rows and columns 2 and 3 RStudio screen shot

Related