R programming advanced Tutorial

R programming advanced Tutorial

Download R

DOWNLOAD RSTUDIO

R programming advanced Tutorial

> a <- c(1,2,3,4,5)
> a
[1] 1 2 3 4 5
> a+1
[1] 2 3 4 5 6
> mean(a)
[1] 3
> var(a)
[1] 2.5

#create a matrix
m <- matrix(1:6 , nrow=2 , rcol=3)

#data frame
x <- data.frame(bar=1:4,foo=c(T,T,T,F))

#large data set, read in RAM
initial<- read.table(“datatable.txt”,nrows=100)

#select non nuls
x<- c(1,2,NA,4,5)
bad <- is.na(x)
good <- complete.cases(x)
x[!bad] x[good]

#select specific column from matrix
col <- complete.cases( airquality[ ,2])

#select specific row from matrix
col <- complete.cases( airquality[1, ])

#loops, while
count <-0
while(count < 10 ){
count=count+1
}
#create a function b and c have default values so we can call f(2,3)
f <- function( a , b=1 , c=”TRUE” , d ){
print(a+b+d)
}

f<-function(x,y){
x^2+y
}

#get the working directory
getwd()

pollutantmean <- function(directory, pollutant, id = 1:332) {
#directory = C:/Users/HALLAM/Documents/specdata/
files <- list.files(directory, full.names = TRUE)
tgt <- lapply(files[id], function(x) read.csv(x, header = TRUE))
result <- lapply(tgt, function(x) x[, pollutant])
pollutants <- unlist(result)
mean(pollutants, na.rm = TRUE)
}

pollutantmean(‘C:/Users/HALLAM/Documents/specdata/’ , “sulfate” )

complete <- function(directory, id = 1:332) {
#directory = C:/Users/HALLAM/Documents/specdata/
files <- list.files(directory, full.names = TRUE)
tgt <- lapply(files[id], function(x) read.csv(x, header = TRUE))
nobs <- sapply(tgt, function(x) sum(complete.cases(x)))
data.frame(‘id’ = id, ‘nobs’ = nobs)

}

 

 

Leave a Reply