Note that there are some explanatory texts on larger screens.

plurals
  1. POReplace last NA of a segment of NAs in a column with last valid value
    text
    copied!<p>Here is a sample data frame:</p> <pre><code>&gt; df = data.frame(rep(seq(0, 120, length.out=6), times = 2), c(sample(1:50, 4), + NA, NA, NA, sample(1:50, 5))) &gt; colnames(df) = c("Time", "Pat1") &gt; df Time Pat1 1 0 33 2 24 48 3 48 7 4 72 8 5 96 NA 6 120 NA 7 0 NA 8 24 1 9 48 6 10 72 28 11 96 31 12 120 32 </code></pre> <p>NAs which have to be replaced are identified by <code>which</code> and logical operators:</p> <pre><code>x = which(is.na(df$Pat1) &amp; df$Time == 0) </code></pre> <p>I know the <code>locf()</code> command, but it's replacing all NAs. How can I replace only the NAs at position x in a multi-column df?</p> <hr> <p>EDIT: Here is a link to my original dataset: <a href="https://www.dropbox.com/s/o9qdkorjnozvwmh/pad_88.csv" rel="nofollow">link</a></p> <p>And thats how far I get: </p> <pre><code>require(reshape2) require(zoo) pad.88 &lt;- read.csv2("pad_88.csv") colnames(pad.88) = c("Time", "Increment", "Side", 4:length(pad.88)-3) attach(pad.88) x = which(Time == 240 &amp; Increment != 5) pad.88 = pad.88[c(1:x[1], x[1]:x[2], x[2]:x[3], x[3]:x[4], x[4]:x[5], x[5]:x[6],x[6]:x[7], x[7]:x[8], x[8]:nrow(pad.88)),] y = which(duplicated(pad.88)) pad.88$Time[y] = 0 pad.88$Increment[y] = Increment[x] + 1 z = which(is.na(pad.88[4:ncol(pad.88)] &amp; pad.88$Time == 0), arr.ind=T) a = na.locf(pad.88[4:ncol(pad.88)]) </code></pre> <p>My next step is something like <code>pat.cols[z] = a[z]</code>, which doesn't work.</p> <hr> <p>That's how the result should look like:</p> <pre><code>Time Increment Side 1 2 3 4 5 ... 150 4 0 27,478 24,076 27,862 20,001 25,261 165 4 0 27,053 24,838 27,231 20,001 NA 180 4 0 27,599 24,166 27,862 20,687 NA 195 4 0 27,114 23,403 27,862 20,001 NA 210 4 0 26,993 24,076 27,189 19,716 NA 225 4 0 26,629 24,21 26,221 19,887 NA 240 4 0 26,811 26,228 26,431 20,001 NA 0 5 1 26,811 26,228 26,431 20,001 25,261 15 5 1 .... </code></pre> <p>The last valid value in col 5 is 25,261. This value replaces the NA at Time 0/Col 5.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload