Guest User

Untitled

a guest
May 24th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. library(tidyverse)
  2. (thewhat <- tibble(sample = 1:10L, y= 1.0, z =2.0))
  3.  
  4. # A tibble: 10 x 3
  5. sample y z
  6. <int> <dbl> <dbl>
  7. 1 1 1. 2.
  8. 2 2 1. 2.
  9. 3 3 1. 2.
  10. 4 4 1. 2.
  11. 5 5 1. 2.
  12. 6 6 1. 2.
  13. 7 7 1. 2.
  14. 8 8 1. 2.
  15. 9 9 1. 2.
  16. 10 10 1. 2.
  17.  
  18. (thewhere <- tibble(cond = c("a","a","b","c","a"),
  19. init_sample= c(1,3,4,5,7),
  20. duration = c(1,2,2,1,3),
  21. where = c(NA,"y","z","y","z")))
  22.  
  23. # A tibble: 5 x 4
  24. cond init_sample duration where
  25. <chr> <dbl> <dbl> <chr>
  26. 1 a 1. 1. <NA>
  27. 2 a 3. 2. y
  28. 3 b 4. 2. z
  29. 4 c 5. 1. y
  30. 5 a 7. 3. z
  31.  
  32. # table with the elements that should be replaced by NA
  33. NAs <- filter(thewhere, cond=="a") %>%
  34. mutate( sample = map2(init_sample, init_sample + duration - 1,seq)) %>%
  35. unnest %>%
  36. select(where, sample)
  37.  
  38. # Takes into account the different columns but I need to manually add each relevant column
  39. # and another case for mutate_all when the where is NA:
  40. mutate(thewhat, y = if_else(sample %in% NAs$sample[NAs$where =="y"],
  41. NA_real_, y ))
  42.  
  43. # A tibble: 10 x 3
  44. sample y z
  45. <int> <dbl> <dbl>
  46. 1 1 NA NA
  47. 2 2 1. 2.
  48. 3 3 NA 2.
  49. 4 4 NA 2.
  50. 5 5 1. 2.
  51. 6 6 1. 2.
  52. 7 7 1. NA
  53. 8 8 1. NA
  54. 9 9 1. NA
  55. 10 10 1. 2.
  56.  
  57. library(tidyverse)
  58. lst <- NAs %>%
  59. split(.$where)
  60. set_names(names(lst), names(lst)) %>%
  61. map_df(., ~ thewhat[[.x]] %>%
  62. replace(., thewhat$sample %in% lst[[.x]]$sample, NA_real_) ) %>%
  63. bind_cols(thewhat %>%
  64. select(sample), .)
  65. # A tibble: 10 x 3
  66. # sample y z
  67. # <int> <dbl> <dbl>
  68. # 1 1 1 2
  69. # 2 2 1 2
  70. # 3 3 NA 2
  71. # 4 4 NA 2
  72. # 5 5 1 2
  73. # 6 6 1 2
  74. # 7 7 1 NA
  75. # 8 8 1 NA
  76. # 9 9 1 NA
  77. #10 10 1 2
Add Comment
Please, Sign In to add comment