Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. set.seed(1)
  2. x <- data.frame(c(1:10),rnorm(10,10, sd = 2.5))
  3. colnames(x) <- c("id", "value")
  4.  
  5. id value
  6. 1 1 8.433865
  7. 2 2 10.459108
  8. 3 3 7.910928
  9. 4 4 13.988202
  10. 5 5 10.823769
  11. 6 6 7.948829
  12. 7 7 11.218573
  13. 8 8 11.845812
  14. 9 9 11.439453
  15. 10 10 9.236529
  16.  
  17. # Let's lose data
  18. (x <- x[-5,])
  19.  
  20. f <- function(x, fill_value){
  21. # Get number of rows
  22. n <- nrow(x)
  23. max_id <- max(x$id)
  24.  
  25. # Get missing data position
  26. no_data_position <- which(!(1:max_id %in% x$id))
  27.  
  28. # Fill missing data
  29. out <- data.frame()
  30. start <- 0
  31. counter <- 1
  32.  
  33. for(i in 1:max_id){
  34. if(!i %in% no_data_position){
  35. out[start + i, "id"] <- start + i
  36. out[start + i, "value"] <- x$value[counter]
  37. counter <- counter + 1
  38. } else {
  39. out[start + i, "id"] <- start + i
  40. out[start + i, "value"] <- fill_value
  41. }
  42. }
  43. return(out)
  44. }
  45.  
  46.  
  47. f(x, NA)
  48.  
  49. id value
  50. 1 1 8.433865
  51. 2 2 10.459108
  52. 3 3 7.910928
  53. 4 4 13.988202
  54. 5 5 NA
  55. 6 6 7.948829
  56. 7 7 11.218573
  57. 8 8 11.845812
  58. 9 9 11.439453
  59. 10 10 9.236529
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement