Guest User

Untitled

a guest
Nov 24th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. data = data.frame(col1 = c(1,2,3,4,5,6,7,8), col2 = c(2,3,'NA',5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,10), col4 = c(2,3,4,1,2,6,7,8),
  2. col5 = c(2,3,'NA','NA',6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA'), col8 = c(1,2,3,4,5,6,'NA','NA'))
  3.  
  4. > print(data)
  5. col1 col2 col3 col4 col5 col6 col7 col8
  6. 1 1 2 3 2 2 1 1 1
  7. 2 2 3 4 3 3 2 2 2
  8. 3 3 NA 5 4 NA 3 3 3
  9. 4 4 5 6 1 NA 5 4 4
  10. 5 5 6 7 2 6 6 6 5
  11. 6 6 7 8 6 7 7 7 6
  12. 7 7 8 9 7 8 8 NA NA
  13. 8 8 9 10 8 9 9 NA NA
  14.  
  15. newcol1 newcol2 newcol3 newcol4
  16. 2 3 2 1.50
  17. 4 4 4 3.50
  18. 6 5.75 6.50 6
  19. 8 8.50 8.50 NA
  20.  
  21. a = 1
  22. b = 2
  23.  
  24. for (i in 1:15) {
  25. test[[i]] = mean(c(data[a,a], data[a,b], data[b,a], data[b,b]))
  26. test[[i]] = mean(c(data[a+i,a+i], data[a+i,b+i], data[b+i,a+i], data[b+i,b+i]))
  27. }
  28.  
  29. a <- as.matrix(data)
  30.  
  31. #adapted from @flodel https://stackoverflow.com/a/16884987/680068
  32. res <- tapply(a, list((row(a) + 1L) %/% 2L, (col(a) + 1L) %/% 2L), mean, na.rm = TRUE)
  33.  
  34. # remove NANs
  35. res[ is.nan(res) ] <- NA
  36. res
  37. # 1 2 3 4
  38. # 1 2 3.00 2.0 1.5
  39. # 2 4 4.00 4.0 3.5
  40. # 3 6 5.75 6.5 6.0
  41. # 4 8 8.50 8.5 NA
  42.  
  43. R8toR4 <- function(mat) {
  44. stopifnot(identical(dim(mat), c(8L, 8L)))
  45.  
  46. out <- matrix(nrow = 4, ncol = 4)
  47.  
  48. for (i in 1:nrow(out)) {
  49. for (j in 1:ncol(out)) {
  50. submatrix <- mat[i * 2 - c(1, 0), j * 2 - c(1, 0)]
  51. if (all(is.na(submatrix))) {
  52. out[i, j] <- NA
  53. } else {
  54. out[i, j] <- mean(submatrix, na.rm = TRUE)
  55. }
  56. }
  57. }
  58.  
  59. out
  60. }
  61.  
  62.  
  63. DataMatrix <- as.matrix(data)
  64. R8toR4(DataMatrix)
  65. [,1] [,2] [,3] [,4]
  66. [1,] 2 3.00 2.0 1.5
  67. [2,] 4 4.00 4.0 3.5
  68. [3,] 6 5.75 6.5 6.0
  69. [4,] 8 8.50 8.5 NA
Add Comment
Please, Sign In to add comment