adding a vector as a column based on matching between another vector and a column

Hi all,

I have this dataset with has two columns:

d <- tibble::tribble(
    ~subject,  ~word, 
    "s1",                "go",
    "s1",                    "sleep",      
    "s1",                "eat",    
    "s1",                    "eat" ,   
    "s2",                    "do"   ,  
    "s2",                    "do"    , 
    "s2",           "walk"     ,
    "s2",                "light"  ,
    "s3",                    "nice"   ,
    "s3",                    "good"   ,
    "s3",                    "pen" ,
    "s3",                    "key"  ,
)

and I also have these two vectors:

s1 = c("q","z","t","p","v","g","s","h","f","y")

s2=c("light","nice","good","pen","key","go","sleep","eat","do","walk")

I want to add s1 as a label column in the data based on the matching between word and s2. The output I am looking for is similar to this:

  subject  word    label 
   <chr>   <chr>
 1 s1      go        g
 2 s1      sleep     s 
 3 s1      eat       h
 4 s1      eat       h
 5 s2      do        f
 6 s2      do        f
 7 s2      walk      y
 8 s2      light     q
 9 s3      nice      z
10 s3      good      t
11 s3      pen       p 
12 s3      key       v

Could anybody help with that?
Thank you in advance!

Hi, you can try turning the s1 & s2 into a named vector:

s3 <- data.frame(name = s2, value = s1) %>% deframe()
s3
light  nice  good   pen   key    go sleep   eat    do  walk 
  "q"   "z"   "t"   "p"   "v"   "g"   "s"   "h"   "f"   "y" 

or directly construct a named vector:

s3 <- c(
  light = "q",
  nice = "z",
  good = "t",
  pen = "p",
  key = "v",
  go = "g",
  sleep = "s",
  eat = "h",
  do = "f",
  walk = "y"
)

and then use vec["name"] to call value from s3

d1 <- d %>% mutate(lable = s3[word])
d1
# A tibble: 12 x 3
   subject word  lable
   <chr>   <chr> <chr>
 1 s1      go    g    
 2 s1      sleep s    
 3 s1      eat   h    
 4 s1      eat   h    
 5 s2      do    f    
 6 s2      do    f    
 7 s2      walk  y    
 8 s2      light q    
 9 s3      nice  z    
10 s3      good  t    
11 s3      pen   p    
12 s3      key   v  
2 Likes

Many thanks, @yifanliu!

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.