Skip to content

Instantly share code, notes, and snippets.

@saraswatmks
Last active December 20, 2017 16:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saraswatmks/ac5b0c9ab2c8940c5edc6999bda6132e to your computer and use it in GitHub Desktop.
Save saraswatmks/ac5b0c9ab2c8940c5edc6999bda6132e to your computer and use it in GitHub Desktop.
Statistics in R
### Median and Quartile
cal_med <- function(x)
{
### median
x<- sort(x)
l1 <- length(x)
mid <- c()
if(l1 %% 2 == 0) mid <- append(mid, c(l1/2, (l1/2)+1))
else mid <- append(mid, ceiling(l1/2))
if(length(mid) != 1)
{
val <- x[mid]
val <- sum(val) / length(val)
# cutoff <- l1/2
} else {
val <- x[mid]
# cutoff <- ceiling(l1/2)
}
return(val)
}
q1_q3 <- function(x)
{
x <- sort(x)
if(length(x) %%2 != 0)
{
cutoff <- ceiling(length(x)/2)
q1_ <- x[1:(cutoff - 1)]#; print(q1_)
q3_ <- x[(cutoff+1):length(x)]#; print(q3_)
} else {
cutoff <- c(length(x)/2)
q1_ <- x[1:cutoff]
q3_ <- x[(cutoff + 1) : length(x)]
}
q1 <- cal_med(q1_)
q3 <- cal_med(q3_)
return(list(q_q1 = q1, q_q2 = q3))
}
### Standard Deviation
find_sd <- function(x)
{
get_mean <- sum(x) / length(x)
int_sum <- c()
for(i in x)
{
int_sum <- append(int_sum, (x - get_mean)^2)
}
int_sum <- sqrt(sum(int_sum)/length(int_sum))
int_sum <- round(int_sum,1)
return(int_sum)
}
### Interquartile range
con <- file('stdin', 'r')
input <- readLines()
n <- input[[1]]
n1 <- input[[2]]
n2 <- input[[3]]
n1 <- as.numeric(unlist(strsplit(n1, ' ')))
n2 <- as.numeric(unlist(strsplit(n2, ' ')))
vec <- rep(n1, n2)
q1_q3 <- function(x)
{
x <- sort(x)
if(length(x) %%2 != 0)
{
cutoff <- ceiling(length(x)/2)
q1_ <- x[1:(cutoff - 1)]#; print(q1_)
q3_ <- x[(cutoff+1):length(x)]#; print(q3_)
} else {
cutoff <- c(length(x)/2)
q1_ <- x[1:cutoff]
q3_ <- x[(cutoff + 1) : length(x)]
}
q1 <- cal_med(q1_)
q3 <- cal_med(q3_)
return(list(q_q1 = q1, q_q3 = q3))
}
q1_res <- q1_q3(vec)$q_q1
q3_res <- q1_q3(vec)$q_q2
iqr <- q3_res - q1_res
cat(iqr)
#### get diagonals from vectors
# Enter your code here. Read input from STDIN. Print output to STDOUT
con <- file('stdin', 'r')
input <- readLines(con)
n <- as.numeric(input[[1]])
diag1 <- c()
diag2 <- c()
for (i in seq(2,n+1))
{
#mats <- append(mats, input[[i]])
d1 <- as.numeric(unlist(strsplit(input[[i]], ' ')))[i-1]
diag1 <- append(diag1, d1)
d2 <- as.numeric(unlist(strsplit(input[[i]], ' ')))[(n+2)-i]
diag2 <- append(diag2, d2)
}
#print(diag2)
cat(abs(sum(diag1) - sum(diag2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment