Short R Codes

The following is a series of sample codes I’ve written in R.

1. This code will take a set of random numbers, and evaluate the mean of every ten numbers.

draws <- rpois (1000, 10)
nseq <- seq(10, 1000, 10)
meanvec <- rep(NA, length(nseq))
for(i in 1:length(nseq)){meanvec[i] <- mean(draws[1:nseq[i]])}
head(meanvec)
sapply(nseq, FUN = function(nseq){mean(draws[1:nseq])})
total <- 1:1000
all <- cumsum(draws)/c(total)
all[nseq]
#This returns 100 means, ranging from a little over 11 to a little under 10.

 

2. This takes any number and evaluate if it qualifies to be a leap year or not. Leap year return TRUE, not leap year returns FALSE.

leapyear <- function(x){
if(x%%4==0 & x%%100!=0){
return(TRUE)
}
if(x%%400==0){
return(TRUE)
}
return(FALSE)
}
Example:
leapyear(2000)
TRUE
leapyear(2001)
FALSE

 

3. This function allows me to take a set of vectors and evaluate which ones are leap years. Leap year returns TRUE, and not leap year returns FALSE.

leapyear <- function(x){
ifelse((x%%4==0 & x%%100!=0) | x%%400==0, TRUE, FALSE)}
Example:
leapyear(c(1000,2000,2001))
FALSE  TRUE FALSE

 

4. This takes a set of vectors and rescale them between the lower and upper inputs. If no lower or upper inputs are input in, default values are lower=0 and upper=1.
#rescales x to lie between lower and upper

rescale <- function(x, lower = 0, upper = 1){
slope <- (upper-lower)/(max(x)-min(x))
intercept <- lower-min(x)*(slope)
y<-intercept + slope * x
return(list(new = y, coef = c(intercept = intercept, slope = slope)))
}
Example:
rescale(c(1000,2000,2001))
$new
0.000000 0.999001 1.000000
$coef
intercept        slope
-0.999000999  0.000999001

Advertisements
%d bloggers like this: