# working with R packages

I am new user R. How can we use effectively any packages.. I only installed packages but can not work them. I use library function but I do not understand afffectly .THANK you .

There is a set of packages called base or R{base} that is always loaded. An example is

> tote <- c(1,3,5,7,9,11)
> mean(tote)
[1] 6
>


Think of R as algebra with f(x) = y \equiv y <- f(x)

In the example above we have two built-in functions c and mean.

c stands for concatenate or combine into a list. mean is just the statistical mean or average of the numbers we assigned to the new variable tote, which we used as the x in f(x) = y and the answer, 6, is y.

There are a few thousand optional libraries in R. You have to install them, using

install.packages("lubridate")


library(lubridate)


The first thing you want to do with a new package is to find out what it's supposed to do

help(lubridate)


In this case you find out that it helps with converting dates from one format to another. At the bottom of the page there will usually be an index. Look at it. For many packages, you will find a mini tutorial link at the top User guides, package vignettes and other documentation. Look at it.

It will give examples. Try them out.

ymd("20110604")
#> [1] "2011-06-04"
mdy("06-04-2011")
#> [1] "2011-06-04"
dmy("04/06/2011")
#> [1] "2011-06-04"


Again, we're seeing three functions with three different arguments.

You will always have a problem whose solution isn't discussed here, so go back to the index and look at the descriptions. Say you want to know if a particular datetime object is in the morning or afternoon. Click on am and you will see a help page.

Look for the example at the bottom

> x <- ymd("2012-03-26")
> am(x)
[1] TRUE
> pm(x)
[1] FALSE


(In case you're wondering a datetime object with no date information is assumed to be in the morning.)

Now go back to the top of the am help page and look at what's called the function's signature

Usage

am(x)
pm(x)

Arguments

x a date-time object


This one is simple it only takes a single argument x, and x has to be a particular type of class, a datetime object, just as you can't divide London/Brusells because cities are not numbers, you can give an arbitrary character string to am

> am("London")
Error in as.POSIXlt.character(x, tz = tz(x)) :
character string is not in a standard unambiguous format
>


Most other functions has signatures with multiple arguments, some mandatory, some optional and some with defaults. The key is to understand what the argument represents, what type of object it is and what the function is supposed to do with it.

Think of R simply as algebra and you'll find it much easier.

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