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

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri May 6 20:17:14 CEST 2022


Hello,

When you unlist, the dimension is dropped since the result is just one 
vector. Add drop = FALSE and that's it.


unlist(df[, "VarY", drop = FALSE])


Hope this helps,

Rui Barradas

Às 19:05 de 06/05/2022, Hooiveld, Guido escreveu:
> 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?
> 
> Thanks,
> Guido
> 
> 
>> 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"]))
> NULL
>>
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list