Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I know what you look for, and that is not implemented in R. I have no knowledge of a package where that is implemented, but it's not too difficult to code it yourself.</p> <p>A workable way is to add a dataframe to the attributes, containing the codes. To prevent doubling the whole dataframe and save space, I'd add the indices in that dataframe instead of reconstructing a complete dataframe.</p> <p>eg :</p> <pre><code>NACode &lt;- function(x,code){ Df &lt;- sapply(x,function(i){ i[i %in% code] &lt;- NA i }) id &lt;- which(is.na(Df)) rowid &lt;- id %% nrow(x) colid &lt;- id %/% nrow(x) + 1 NAdf &lt;- data.frame( id,rowid,colid, value = as.matrix(x)[id] ) Df &lt;- as.data.frame(Df) attr(Df,"NAcode") &lt;- NAdf Df } </code></pre> <p>This allows to do :</p> <pre><code>&gt; Df &lt;- data.frame(A = 1:10,B=c(1:5,-1,-2,-3,9,10) ) &gt; code &lt;- list("Missing"=-1,"Not Answered"=-2,"Don't know"=-3) &gt; DfwithNA &lt;- NACode(Df,code) &gt; str(DfwithNA) 'data.frame': 10 obs. of 2 variables: $ A: num 1 2 3 4 5 6 7 8 9 10 $ B: num 1 2 3 4 5 NA NA NA 9 10 - attr(*, "NAcode")='data.frame': 3 obs. of 4 variables: ..$ id : int 16 17 18 ..$ rowid: int 6 7 8 ..$ colid: num 2 2 2 ..$ value: num -1 -2 -3 </code></pre> <p>The function can also be adjusted to add an extra attribute that gives you the label for the different values, see also <a href="https://stackoverflow.com/questions/5333280/what-is-the-official-way-of-creating-structuring-maintaining-and-updating-dat">this question</a>. You could backtransform by :</p> <pre><code>ChangeNAToCode &lt;- function(x,code){ NAval &lt;- attr(x,"NAcode") for(i in which(NAval$value %in% code)) x[NAval$rowid[i],NAval$colid[i]] &lt;- NAval$value[i] x } &gt; Dfback &lt;- ChangeNAToCode(DfwithNA,c(-2,-3)) &gt; str(Dfback) 'data.frame': 10 obs. of 2 variables: $ A: num 1 2 3 4 5 6 7 8 9 10 $ B: num 1 2 3 4 5 NA -2 -3 9 10 - attr(*, "NAcode")='data.frame': 3 obs. of 4 variables: ..$ id : int 16 17 18 ..$ rowid: int 6 7 8 ..$ colid: num 2 2 2 ..$ value: num -1 -2 -3 </code></pre> <p>This allows to change only the codes you want, if that ever is necessary. The function can be adapted to return all codes when no argument is given. Similar functions can be constructed to extract data based on the code, I guess you can figure that one out yourself.</p> <p>But in one line : using attributes and indices might be a nice way of doing it.</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