Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dataframe columns to named number vector [duplicate]

Tags:

r

I have a dataframe blah:

blah <- data.frame(x=c("Red", "Blood Red", "Crimson", "Maroon"), y=c(20, 1, 14, 13))

I want to convert blah into a named number/member vector:

blah <- c(`Red` = 20, `Blood Red` = 1, `Crimson` = 14, `Maroon` = 13)

Where x is the name and y is the value.

How can I make this happen?

like image 554
emehex Avatar asked Feb 23 '26 16:02

emehex


1 Answers

Just use setNames

setNames(blah$y, blah$x)
# Red Blood Red   Crimson    Maroon 
#  20         1        14        13 
like image 105
David Arenburg Avatar answered Feb 25 '26 06:02

David Arenburg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!