Guest User

Untitled

a guest
Feb 17th, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. # Enter your code here. Read input from STDIN. Print output to STDOUT
  2. stdin <- file('stdin')
  3. open(stdin)
  4. # Input Format
  5. # The first line contains the number of integers.
  6. # The second line contains space separated integers for which you need to find the mean, median, mode, standard deviation and confidence interval boundaries.
  7.  
  8. # Read the second line
  9. input <- readLines(stdin, warn = FALSE)[[2]]
  10. #cat(input)
  11. elements <- c()
  12. # count total elements in the input
  13. n <- length(as.numeric(unlist(strsplit(input, split=" "))))
  14.  
  15. # Loop through the elements
  16. for (i in 1:n) {
  17. # read each element
  18. tmp = as.numeric(unlist(strsplit(input, split=" "))[i])
  19. elements[i] <- tmp
  20. }
  21. # mean
  22. mean <- mean(elements, na.rm = FALSE)
  23. # median
  24. median <- median(elements, na.rm = FALSE)
  25. # mode
  26. CalcMode <- function(x) {
  27. ux <- unique(sort(x))
  28. ux[which.max(tabulate(match(x, ux)))]
  29. }
  30. mode = CalcMode(elements)
  31.  
  32. # standard deviation
  33. # sqaure root of the average squared distance from the mean
  34. Calcsd<- function(x,n,m) {
  35. # calculate average squared distance
  36. #sqrt(sum((a-mean(a))^2/(length(a)-1)))
  37. a = sum((x - m)^2)
  38. b = a/n
  39. c = sqrt(b)
  40. c= round(c,1)
  41. }
  42. #sd <- sd(elements,na.rm = FALSE)
  43. sd <- Calcsd(elements,n,mean)
  44.  
  45. #CI
  46. error <- 1.96 * sd * (1/sqrt(n))
  47. error <- round(error,1)
  48. lower = mean - error
  49. upper = mean + error
  50.  
  51. # output
  52. cat(mean, sep="\n")
  53. cat(median, sep="\n")
  54. cat(mode, sep="\n")
  55. cat(sd, sep="\n")
  56. cat(lower,upper)
  57. #cat(upper)
  58. close(stdin)
Add Comment
Please, Sign In to add comment