What does putting "as." in front of numeric or factor accomplish?


I am confused about what the "as." command is used for and when it is appropriate to use. Could you please clarify the use of the "as."
command and why we need it?

Thank you

Answers and follow-up questions

Answer or follow-up question 1

The short form (without "as.") is to initialize an empty vector, whereas the long form (with "as.") is to
coerce (transform) a vector to a specific class. Initialization of vectors is recommended whenever
you do a loop.

For example if you do ?numeric you'll see in the Usage Section:

numeric(length = 0)
as.numeric(x, ...)

Thus the short form has one parameter called length. The long form has a parameter called x.

In the Arguments Section you'll see:
-length is an integer specifying the desired length
-x is the object to be coerced

For example:
#Initialize a numeric vector
> numeric(5)
[1] 0 0 0 0 0

#Coerce a character vector to numeric
> (a <- as.character(seq(1.1,1.5,length.out=5)))
[1] "1.1" "1.2" "1.3" "1.4" "1.5"
> as.numeric(a)
[1] 1.1 1.2 1.3 1.4 1.5

Michel Ballings

Sign in to be able to add an answer or mark this question as resolved.