[R] How to obtain named vector from single-column data frame?

Hooiveld, Guido gu|do@hoo|ve|d @end|ng |rom wur@n|
Fri May 6 20:05:13 CEST 2022

Dear all,

I wrote a some code in which I 'convert' a data frame to a named vector using the function unlist(). This works very nicely for my use case, because each entry of the resulting vector is named after the column name of the data frame, with a number automatically appended. I am using these names for the subsequent part of my code.

However, I noticed that when I subset the data frame so it contains only a single column, the naming of the vector (as described above) doesn't occur anymore (i.e. names() = NULL). This breaks my downstream code. Any suggestion on how to still obtain a named vector from such single-column data frame?


> df <- data.frame("VarX" = c("A",2,"D",2,1) ,
+  "VarY" = c(5,7,9,8,7) )
> unlist(df) #nice!
VarX1 VarX2 VarX3 VarX4 VarX5 VarY1 VarY2 VarY3 VarY4 VarY5 
  "A"   "2"   "D"   "2"   "1"   "5"   "7"   "9"   "8"   "7" 
> names(unlist(df))
 [1] "VarX1" "VarX2" "VarX3" "VarX4" "VarX5" "VarY1" "VarY2" "VarY3" "VarY4"
[10] "VarY5"
> unlist(df[, "VarY"]) #where are the names now? Expected them to be "VarY1" ... "VarY5"
[1] 5 7 9 8 7
> names(unlist(df[, "VarY"]))

More information about the R-help mailing list