Code Note

JHU R Programming Course Note

Gathering long list of file names:

files_list <- list.files(directory, full.name=TRUE)

Construct a data.frame by rowbind

dat <- rbind(dat,read.csv(files_list[i]))

#Understanding lexical scoping
#<- operator vs. <<- operator
crazy <- function() {
x <<- 3.14 #variable x in the containing environment is updated to be 3.14
print(x) #no local variable x exists within functin ‘crazy’ R searches the containing environments
{print(x);
x <- 42; print(x) #local variable x is declared and assigned the value 42; overrides the variable x in
} #the containing environment
print(x) #since local variable x now exists within the function there is no need to search the containing
} #environment

x #variable x outside the function is updated value after the first statement within function crazy()
#the super-assignment operator does not update a variable of the same name inside an inner function but the innermost environment
#inherits any changes unless a local variable of the same name exists within the inner function as demonstrated
#by x <- 42;

crazy <- function() {
x <- 42
x <<- 3.14
print(x)
}

#> x <-0
#> x
#[1] 0
#> crazy()
#[1] 42
#> x
#[1] 3.14

#Declare and define a function named crazy()
crazy <- function() {
x <- 3.14 #asigns the value 3.14 to local variable x not the variable x in the containing environment
print(x)

{print(x);
x <<- 42; # assigns the value 42 to variable x in the containing environment
print(x)
}
print(x)
}

#> x <-0
#> x
#[1] 0
#> crazy()
#[1] 3.14
#[1] 3.14
#[1] 3.14
#[1] 3.14
#> x
#[1] 42

makeVector <- function(x = numeric()){
m <- NULL
set <- function(y){
x <<- y
m <<- NULL
}
get <- function()x
setmean <- function(mean)m <<-mean
getmean <- function()m
list(set=set, get=get,
setmean=setmean,
getmean=getmean)
}

cachemean <- function(x, …){
m <- x$getmean()
if(!is.null(m)){
message(“getting cached data”)
return(m)
}
data <- x$get()
m <- mean(data,…)
x$setmean(m)
m
}

Split and Lapply

        bystate <- split(rawData, rawData$State)

        result <- lapply(bystate, function(x) x[order(x[,11], x[,2]),])

        hospital<- lapply(result, function(x) x[num,c(2,7)])

        rank <- do.call(rbind, hospital)