Home > Back-end >  Unable to combine two variables in R
Unable to combine two variables in R

Time:01-25

I have this object 'lst` like so

> lst
$vals
[1] ""           "Dark Green" "Orange"     "Yellow"     "Grey"      

$hues
[1] ""          "darkgreen" "orange"    "yellow"    "grey"     

$labs
[1] ""          "darkgreen" "orange"    "yellow"    "grey"     

I then tried to combine values from elements of lst but encountered this error

# Scenario 1:
c(l$vals[2] = l$hues[2]) # l$vals[2] is 'Dark Green' and l$hues[2] is 'darkgreen'
Error: unexpected '=' in "c(l$vals[2] ="

On the other hand, I could do this:

# Scenario 2:
c('Dark Green' = 'darkgreen')

What had happened? Why did Scenario 1 return an error?

CodePudding user response:

This is not going to work, you could do setNames(l$hues[2],l$vals[2]), or some vectorized version setNames(l$hues,l$vals).

CodePudding user response:

You are trying to make a named vector. One way to solve this is to break it up like this

colors <- c(l$hues[2]) 
names(colors) <- c(l$vals[2])

But maybe there are more suitable classes for what you are trying to accomplish?

  •  Tags:  
  • r
  • Related