0

I have a data frame like this:

 data.frame(
   id = rep(1:5, each = 4), 
   status = c(
   NA, "a", "c", "a", 
   "a", "a", "c", "c",
   NA, NA, "c", "c",
   "c", NA, "a", "c",
   "a", NA, "c", NA),
   stringsAsFactors = FALSE)

My primary aim is to carry the string "c" forward within a group (same id). As soon that there appears a "c" within an id, I want the following elements within that group/id to be "c" 's. For example the variable status for id 1 should look like NA, "a", "c", "c".

My second aim would be to remove records/rows with NA's before an a. The variable status for id 1 would then look like "a", "c", "c".

My third aim would be to carry the string "c" backwards until the first "a" (if there was not an "c" in front of that "a") or to the end of the group. For id 3 this would look like "c","c","c","c". And for id 5 this would look like "a", "c", "c", "c".

Ideally my data frame would look like:

status:  a,c,c,  a,a,c,c,  c,c,c,c,  c,c,c,c,  a,c,c,c.

I figured out that you can use na.locf to carry forward an element if there are NA's following but I don't think that this works if I want to overwrite/replace the following values other than NA.

I am particularly interested in how to solve my primary aim. Is this possible?

Roccer
  • 899
  • 2
  • 10
  • 25
  • It would be nice if Sotos could properly read this question before marking it as duplicate. I specifically mentioned that this question is not only about replacing NA's but also other strings after the string that should be carried forward. – Roccer May 03 '18 at 12:24
  • It would also be nice If you provided us with the code that you have tried and failed in order to see where you have the issue. SO is not a code writing service. I reopened the question. – Sotos May 03 '18 at 14:07

0 Answers0