> For the complete documentation index, see [llms.txt](https://r-pedia.gitbook.io/cevi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r-pedia.gitbook.io/cevi/r-data/r-management.md).

# -R management

## #R functions for objects

&#x20;Useful functions for dealing with objects

```r
rm(list=ls()) #delete all objectslength(object) 
# number of elements str(object)    
# structure of an object class(object)  
# class or type of an objectnames(object)  
# names of a objectobject     
# prints the objectls()       
# list current objectsrm(object) 
# delete an objectc(object,object,...)       
# combine objects into a vectorcbind(object, object, ...) 
# combine objects as columnsrbind(object, object, ...) 
# combine objects as rows ​
```

## #R data import/export

&#x20;Importing data into R is fairly easy methode. The important thing that you must know the function for every sources. The most sources from getting data in R come from CSV plain text and Excel.

#### #1- Import from CSV plain text: [read.table()](https://www.rdocumentation.org/packages/utils/versions/3.4.3/topics/read.table)​ <a href="#id-1-import-from-csv-plain-text-read-table" id="id-1-import-from-csv-plain-text-read-table"></a>

* If you’ve already [set a working directory in R](https://itsmecevi.gitbook.io/r/untitled-1/r-folder):

```r
csvdata <- read.table("csv.txt", header=TRUE,sep=",")
```

* If you haven't set a working directory: **copy the file and paste in file directory (PASTE HERE)**

```
csvdata<-read.table("PASTE HERE",header=TRUE,sep=",")
```

* Export as CSV

```
 write.table(csvdata, "c:/mydata.txt", sep=",")
```

Save the dataset as .csv with plain text editor or another program such as excel

```
Sally Whittaker,2018,McCarren House,312,3.75
Belinda Jameson,2017,Cushing House,148,3.52
Jeff Smith,2018,Prescott House,17-D,3.20
Sandy Allen,2019,Oliver House,108,3.48
```

#### &#x20;#2-Import from Excel:  <a href="#id-2-import-from-excel" id="id-2-import-from-excel"></a>

* The best ways to read an Excel file is to export it to a csv , but we can do it direct in R

```r
library(readxl) #install the readxl package
dataexcel <- read_excel("excel.xlsx") 
#saving the data into a variableView(dataexcel) 
```

Note: If you haven't set a working directory: copy the file and paste in function read\_excel("PASTE HERE")

* Export as excel.xlsx?????

```
```

&#x20;**Going further** : [R Data Import Tutorial](https://www.datacamp.com/community/tutorials/r-data-import-tutorial) and [R Data Import/Export](https://cran.r-project.org/doc/manuals/r-release/R-data.html)

## #R dataset information

&#x20;How to get information from the dataset

```r
# See the dataset
dataset
#or
print(dataset)
#or
View(dataset
# print first 10 rows of dataset
head(dataset, n=10)
# print last 7 rows of dataset
tail(dataset, n=7)
# list all objects 
ls()
# list the variables 
names(dataset)
# list the structure of dataset
str(dataset)
# class of an object or variable (numeric, matrix, data frame, etc)
class(object)
# dimensions of an object
dim(object) 
```

## #R missing data

&#x20;The symbol NA (not available) are represented missing value. And NaN are not a number (e.g., dividing by zero).

Going further for more [NaN values](https://en.wikipedia.org/wiki/NaN)

#### Missing Values test: <a href="#missing-values-test" id="missing-values-test"></a>

```
x<- c(1,2,3,NA)
is.na(x) # returns a vector (F F F T)
############
[1] FALSE FALSE FALSE  TRUE
```

#### Excluding Missing Values from Analyses: <a href="#excluding-missing-values-from-analyses" id="excluding-missing-values-from-analyses"></a>

```
x <- c(1,2,NA)
mean(x) # returns NA
mean(x, na.rm=TRUE) # returns 1.5
#######
[1] 1.5
```

#### Advanced Handling of Missing Data: <a href="#advanced-handling-of-missing-data" id="advanced-handling-of-missing-data"></a>

* &#x20;[Amelia II](http://gking.harvard.edu/amelia/), [Mice](https://www.rdocumentation.org/packages/mice/versions/2.25/topics/mice), and [mitools](http://cran.us.r-project.org/web/packages/mitools/index.html).

## #R date Values

&#x20;Dates are represented as the number of days since 1970-01-01, with negative values for earlier dates.

&#x20;Convert strings to dates and opposite:

```r
# convert strings dates with as.Date( ) 
dates <- as.Date(c("2018-04-22", "2014-02-13"))
# number of days between date
days <-dates[1] - dates[2] #Time difference of 1529 day# 
#convert dates to character datastr
Dates <- as.character(days)
```

#### Todays date and time: <a href="#todays-date-and-time" id="todays-date-and-time"></a>

```r
Sys.Date( ) #returns today's date. 
date() #returns the current date and time.
```

* &#x20;**format( )** function to print dates.

| **Symbol** | **Meaning**            | **Example** |
| ---------- | ---------------------- | ----------- |
| **%Y**     | 4-digit year           | 2007        |
| **%y**     | 2-digit year           | 07          |
| **%B**     | unabbreviated month    | January     |
| **%b**     | abbreviated month      | Jan         |
| **%m**     | month (00-12)          | 00-12       |
| **%A**     | unabbreviated weekday  | Monday      |
| **%a**     | abbreviated weekday    | Mon         |
| **%d**     | day as a number (0-31) | 01-31       |

* **An example:**

```r
  #today's date   
  now <- date()   
  format(now, format="%B %d %Y
```

## #R create variable

&#x20;Use operator "<-" or "=" to create variable

#### Assign a variable: <a href="#assign-a-variable" id="assign-a-variable"></a>

```r
cevi<-c(1:10)
data<-c("Berlin", "Frankfurt")
```

#### Categorial variable: <a href="#categorial-variable" id="categorial-variable"></a>

```r
data<-c(1:10)
datacat<-ifelse(data%%2,"odd num","even num") 
#odd num:= modulo 2 (%%2)
datacat
############
[1] "odd num"  "even num" "odd num"  "even num" "odd num"  "even num"
[7] "odd num"  "even num" "odd num"  "even num"
```

## #R operators

#### Arithmetic Operators: <a href="#arithmetic-operators" id="arithmetic-operators"></a>

| **Operator**  | **Description**             |
| ------------- | --------------------------- |
| **+**         | addition                    |
| **-**         | subtraction                 |
| **\***        | multiplication              |
| **/**         | division                    |
| **^ or \*\*** | exponentiation              |
| **x %% y**    | modulus (x mod y) 5%%2 is 1 |
| **x %/% y**   | integer division 5%/%2 is 2 |

#### Logical Operators: <a href="#logical-operators" id="logical-operators"></a>

| **Operator**  | **Description**          |
| ------------- | ------------------------ |
| ​ **==**      | exactly equal to         |
| **!=**        | not equal to             |
| **>**         | greater than             |
| **>=**        | greater than or equal to |
| **<**         | less than                |
| **<=**        | less than or equal to    |
| **!x**        | Not x                    |
| **x \| y**    | x OR y                   |
| **x & y**     | x AND y                  |
| **isTRUE(x)** | test if X is TRUE        |

```
# example 
x <- c(1:5) 
x[(x>1) & (x<5)] 
####################
# result: 2 3 4   
# how it works? 
#x <- c(1:5)
# x
# 1 2 3 4 5 
# x > 1
# F T T T T  
# x < 5
# T T T T F 
# x > 1 & x < 5
# F T T T F 
# x[c(F,T,T,T,F)]
# 2 3 4 
```

## #R built in functions-X

&#x20;Numeric Functions:

| **Function**                                 | **Description**                |
| -------------------------------------------- | ------------------------------ |
| **abs(***x***)**                             | absolute value                 |
| **sqrt(***x***)**                            | square root                    |
| **log(***x***)**                             | natural logarithm              |
| l**og10(***x***)**                           | common logarithm               |
| **exp(***x***)**                             | e^*x*                          |
| **cos(***x***), sin(***x***), tan(***x***)** | -                              |
| **signif(***x***, digits=***n***)**          | signif(3.475, digits=2) is 3.5 |
| **round(***x***, digits=***n***)**           | round(3.475, digits=2) is 3.48 |
| **trunc(***x***)**                           | trunc(5.99) is 5               |
| **floor(***x***)**                           | floor(3.475) is 3              |
| **ceiling(***x***)**                         | ceiling(3.475) is 4            |

Character Functions:

| **Function**                                       | **Description**                                                                                            |
| -------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| **tolower(***x***)**                               | Lowercase                                                                                                  |
| **toupper(***x***)**                               | Uppercase                                                                                                  |
| **substr(***x***, start=***n1***, stop=***n2***)** | Extract or replace substrings x <- "abcdef" substr(x, 2, 3) is "bc" substr(x, 2, 4) <- "22222" is "a22def" |
| **strsplit(***x***,** *split***)**                 | Split the elements strsplit("abc", "") returns 3 element vector "a","b","c"                                |
| **paste(..., sep="")**                             | ​                                                                                                          |

## #R control structures-X
