Reputation: 4681
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
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