BICube
BICube

Reputation: 4681

Converting a dataframe of label/values to a named numeric vector

I am trying to convert a dataframe with labels/values to a named numeric vecotr. For example I have the following dataframe

>df=data.frame(lab=c("A","B","C","D"),values=c(1,2,3,4))  
> df  
   lab values  
1   A      1  
2   B      2  
3   C      3  
4   D      4  

So what I am trying to do is to iterate or use a function on this data frame to get the following

>v_needed=c("A"=1,"B"=2,"C"=3,"D"=4)  
> v_needed  
A B C D   
1 2 3 4 

I tried to convert this to a factor but it didn't give the desired output

>v_failure=factor(df$values,labels=df$lab)

Upvotes: 0

Views: 1222

Answers (1)

MrFlick
MrFlick

Reputation: 206232

You can use the setNames function

v <- with(df, setNames(values, lab))
v
# A B C D 
# 1 2 3 4 

Upvotes: 3

Related Questions