How to replace certain data frame value with it's unknown column name? : <p>I have a large data frame with unknown column names and numeric values 1, 2, 3, or 4.
Now I want to replace all 4 values with it's column name and all 1, 2 and 3's with an empty value. </p>

<p>Ofcourse I can make a loop of some kind, like this:</p>

<pre><code>df &lt;- data.frame(id=1:8,unknownvarname1=c(1:4,1:4),unknownvarname2=c(4:1,4:1))
for (i in 2:length(df)){
  df[,i] &lt;- as.character(df[,i])
  df[,i] &lt;- mgsub::mgsub(df[,i],c(1,2,3,4),c("","","",names(df)[i]))  
}
</code></pre>

<p>This would be the result:</p>

<pre><code>  id unknownvarname1 unknownvarname2
1  1                 unknownvarname2
2  2                                
3  3                                
4  4 unknownvarname1                
5  5                 unknownvarname2
6  6                                
7  7                                
8  8 unknownvarname1 unknownvarname2
</code></pre>

<p>For a data frame this size that's no problem at all. But when I try this loop on large data frames with up to 30k and up to 40 uknown variables, the loop takes ages to complete.</p>

<p>Does anyone know of a faster way to do this? I tried functions like <code>mutate()</code> of <code>dplyr package</code> but I could not manage to make it work.</p>

<p>Many thanks in advance!</p>
