1

As always, I'm here after checking tons of information about coding. Let me explain the situation I'm faced right now: I'm working on a psychological scale that aims to access child development. In this scale, we have no possibility of missing cases, only 0, 1, or 2. Unfortunately, people coded some values with missing and I'm struggling to fix that.

All missing cases must be filled with the following criteria:

if the actual variable is missing AND If the next variable is 2, then the missing will be "2"; if the next variable is 1, then the missing will be "1", if the next variable is 0, then the missing will be "0"

The last column will not be included in the script.

Pretty easy to talk about it, but it's challenging me to code that.

My intuitive coding says something like that:

for (i in 1:ncol(ds)) {
  if(is.na(ds[i]) & ds[i+1] == "2") ds[i] == "2"
}

And the code you can reproduce to work on is:

ds <- data.frame(x1 = rep(sample(0:2),5), 
                 x2 = sample(0:2),
                 x3 = sample(0:2),
                 x4 = sample(0:2))
ds[ds == 0] <- NA

for (i in 1:ncol(ds)) {
  if(is.na(ds[i]) & ds[i+1] == "2") ds[i] == "2"
}

Just to clarify, I know tidyverse (broom) is really useful for situations like that and I'll be happy if someone could explain that using tidyverse environment.

Thanks a lot!

Edited: If you are here to check the answer, feel welcome! But you can go as well to Function / Loop to Replace NA with values in adjacent columns in R . Thanks much!

Luis
  • 1,388
  • 10
  • 30
  • Related: [Function / Loop to Replace NA with values in adjacent columns in R](https://stackoverflow.com/questions/38463511/function-loop-to-replace-na-with-values-in-adjacent-columns-in-r) – Henrik Oct 09 '18 at 16:53
  • @Henrik, Thank you so much! I see the question is pretty much similar to mine! I have edited my question to point to this url you provide me. Thanks much again! – Luis Oct 09 '18 at 17:08

1 Answers1

2

May be we need fill

library(tidyverse)
ds %>% 
  fill(everything(), .direction = 'up')

If we want to do this for each row, then use apply

library(zoo)
ds[] <- t(apply(ds, 1, function(x) na.locf(x, fromLast = TRUE, na.rm = FALSE)))

or with pmap

pmap(ds, ~ c(...) %>%
             as_tibble %>%
             fill(value, .direction= 'up')) %>% 
   bind_cols %>%
   t %>%
   as_tibble
akrun
  • 874,273
  • 37
  • 540
  • 662
  • You are always helping me! Thanks. But I need something like . direction = "right". Is it possible? Thanks! – Luis Oct 09 '18 at 16:47
  • @Luis I think you need for each row, then use `apply` with `na.locf` – akrun Oct 09 '18 at 16:51
  • 1
    One more time you are solving my problems... Thanks much. Now it worked pretty well! – Luis Oct 09 '18 at 17:08