title: R: Assign variable labels of data frame columns
body: <p>I am struggling with variable labels of data.frame columns. Say I have the following data frame (part of much larger data frame):</p>
  
  <pre><code>data &lt;- data.frame(age = c(21, 30, 25, 41, 29, 33), sex = factor(c(1, 2, 1, 2, 1, 2), labels = c("Female", "Male")))
  #
  </code></pre>
  
  <p>I also have a named vector with the variable labels for this data frame:</p>
  
  <pre><code>var.labels &lt;- c(age = "Age in Years", sex = "Sex of the participant")
  </code></pre>
  
  <p>I want to assign the variable labels in <code>var.labels</code> to the columns in the data frame <code>data</code> using the function <code>label</code> from the <code>Hmisc</code> package. I can do them one by one like this and check the result afterwards:</p>
  
  <pre><code>&gt; label(data[["age"]]) &lt;- "Age in years"
  &gt; label(data[["sex"]]) &lt;- "Sex of the participant"
  &gt; label(data)
                   age                      sex
        "Age in years" "Sex of the participant"
  </code></pre>
  
  <p>The variable labels are assigned as attributes of the columns:</p>
  
  <pre><code>&gt; attr(data[["age"]], "label")
  [1] "Age in years"
  &gt; attr(data[["sex"]], "label")
  [1] "Sex of the participant"
  </code></pre>
  
  <p>Wonderful. However, with a larger data frame, say 100 or more columns, this will not be convenient or efficient. Another option is to assign them as attributes directly:</p>
  
  <pre><code>&gt; attr(data, "variable.labels") &lt;- var.labels
  </code></pre>
  
  <p>Does not help. The variable labels are not assigned to the columns:</p>
  
  <pre><code>&gt; label(data)
  age sex
   ""  ""
  </code></pre>
  
  <p>Instead, they are assigned as an attribute of the data frame itself (see the last component of the list):</p>
  
  <pre><code>&gt; attributes(data)
  $names
  [1] "age" "sex"
  
  $row.names
  [1] 1 2 3 4 5 6
  
  $class
  [1] "data.frame"
  
  $variable.labels
                   age                      sex
        "Age in Years" "Sex of the participant"
  </code></pre>
  
  <p>And this is not what I want. I need the variable labels as attributes of the columns. I tried to write the following function (and many others):</p>
  
  <pre><code>set.var.labels &lt;- function(dataframe, label.vector){
    column.names &lt;- names(dataframe)
    dataframe &lt;- mapply(label, column.names, label.vector)
    return(dataframe)
  }
  </code></pre>
  
  <p>And then execute it:</p>
  
  <pre><code>&gt; set.var.labels(data, var.labels)
  </code></pre>
  
  <p>Did not help. It returns the values of the vector <code>var.labels</code> but does not assign the variable labels. If I try to assign it to a new object, it just contains the values of the variable labels as a vector.</p>