0

I would like to use values from a character vector that I created as label attributes for a set of variables in a dataframe.

I thought this simple solution should work, yet it does not:

x <- rep("text", time=19) %>% 
  paste(1:19, sep = " ")  #character vector with names of label attributes I want

attr(mydataframe[var_names], "label") <- x #var_names and x have the same length

Thanks for your help!

ZenSam
  • 1
  • 1
    Welcome to stackoverflow! I'm not sure I understand your question. Do you want the column names of your data.frame to be `x`? If so, try `colnames(mydataframe) <- x` – C-x C-c Aug 31 '18 at 13:13
  • Thanks for your welcome and such a fast reply! I would like to automatically assign label atributes for a subset of variables within a dataframe. The solution by G. Grothendieck works, I rewrote it to use with no hmisc. If smdy knows another way, I would like to learn it. – ZenSam Aug 31 '18 at 14:52

1 Answers1

0

Hmisc supports column labels. Using the built in data frame anscombe having 8 columns:

library(Hmisc)

x <- paste("label", i)

for(i in seq_along(anscombe)) label(anscombe[[i]]) <- x[i]
Label(anscombe)

giving:

label(x1)       <- 'label 1'
label(x2)       <- 'label 2'
label(x3)       <- 'label 3'
label(x4)       <- 'label 4'
label(y1)       <- 'label 5'
label(y2)       <- 'label 6'
label(y3)       <- 'label 7'
label(y4)       <- 'label 8'
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
  • Thanks, I used your idea to work with attributes (no hmisc required) `for (i in seq_along(mydata)) { attr(mydata[[i]], "label") <- x[[i]] #x contains labels I need }` – ZenSam Aug 31 '18 at 14:42
  • Then you are missing out on the "labelled" class methods that Hmisc provides. – G. Grothendieck Aug 31 '18 at 21:19