Is attr() working with df$colname but not with df[,colnumber] ?


I would like to change "label" attribute in a tibble sourced from an SPSS sav file.
I noticed that the following notation works:
attr(df$colname, "label")
as it gives me the label value as found in original sav file, whereas
attr(df[,colnumber], "label")
returns NULL (where colnumber is an actual number of a column)
Why is this? Am I coding something wrong.

The reason: I am trying to make a for loop to change one part of several labels at once using gsub.
It works with first notation, but I can only make a for loop using second notation, where colnumber is changing. This is why I would like attr() to work in the second case presented above.
Any suggestions are welcome.

(hiris <- head(iris))

attr(hiris$Species,"label") <- "some label"



mycolnumber <- 5


What's the issue ? is your colnumber simply wrong perhaps ?

Your code worked for me too. But when I tried this:

write_sav(hiris, "../hiris.sav")

h <- read_sav("../hiris.sav")

attr(h[,5], "label")   #1
attr(h$Species, "label")    #2

I could replicate the problem. #1 does show "NULL" while #2 shows "some label" on my machine...
Could it be that tibble is working different than a df?
class(h) gives out "tbl_df" "tbl" "data.frame"

Ok, your issue comes from difference in subsetting between data.frame and tibble (haven is making a tibble for you). Reference : Subsetting tibbles — subsetting • tibble (

Two options, convert to data.frame and continue as before.
or use additional syntax with the tibble
that would be

attr(h[,5, drop=TRUE], "label")

Thank you - this works, and thanks for the reference :slight_smile:

It turns out this also works

attr(h[[5]], "label")

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.