She Loves Data: R Workshop Day 1 – Basic Data Type Conversion

SheLovesData - R Workshop

It works similarly to other programming languages, in R, it has.
– use is.xxx() to check the data type is of ‘xxx’ type and returns TRUE or FALSE.
– use as.xxx() to convert it into ‘xxx’ type.

Example,

  • is.numeric(), is.integer(), is.character(), is.vector(), is.matrix(), is.data.frame()
  • as.numeric(), as.integer(), as.character(), as.vector(), as.matrix(), as.data.frame)

I have tried to use as.integer() previously, still remember?

 #When I execute the line, y = as.integer(3), the output is,

y = as.integer(3)
class(y)
[1] "integer"

With as.integer, it converts the “3” into integer data type and when use the class(y) it returns integer. Another one which can be used quite often is as.character(), convert a number into a string.

More data conversion is showed in the chart below, it is taken from, https://www.statmethods.net/management/typeconversion.html

After talking so much for character, numeric, string and Boolean, how about Date? Do we able to convert date?

Answer is yes. It has as.date() to convert character into date with default format, yyyy-mm-dd. Of course, we can change the date format. Example, it could be coded as,

as.Date(x, “format”)

where the date formatting can refer to below table,

Right now, I do not have much examples to show data conversion and formatting. Hopefully in the future posts, there will be more sample codes written with data conversion or formatting.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s