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

David Carlson dc@r|@on @end|ng |rom t@mu@edu
Fri May 6 20:26:25 CEST 2022


Just use
names(unlist(df[, "VarY", drop=FALSE]))
# [1] "VarY1" "VarY2" "VarY3" "VarY4" "VarY5"

When you extract a single column from a data frame it converts it to a
vector by default.

David L Carlson



On Fri, May 6, 2022 at 1:05 PM Hooiveld, Guido <guido.hooiveld using wur.nl>
wrote:

> 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,
> ZjQcmQRYFpfptBannerStart
> This Message Is From an External Sender
> This message came from outside your organization.
>
> ZjQcmQRYFpfptBannerEnd
>
> 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, seehttps://urldefense.com/v3/__https://stat.ethz.ch/mailman/listinfo/r-help__;!!KwNVnqRv!EUndg3P-mraBuPMXbhvgZkIok13frVGjcD2ebHWlTHVrETkmNqEfYu0YPT6BEisdkhcijOfxsGlfsGoPXEBOEqSIog$
> PLEASE do read the posting guide https://urldefense.com/v3/__http://www.R-project.org/posting-guide.html__;!!KwNVnqRv!EUndg3P-mraBuPMXbhvgZkIok13frVGjcD2ebHWlTHVrETkmNqEfYu0YPT6BEisdkhcijOfxsGlfsGoPXECRkw_-4w$
> and provide commented, minimal, self-contained, reproducible code.
>
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list