rjt
rjt

Reputation: 39

Paste string if condition matches

I have a small question regarding to paste function in r. Here is my Table:

Name        Value
AA          0       
BB          1       
CC          0   
DD          1       
EE          1       
FF          1       
GG          0   
HH          1

What I want to do is to get another column nameed Category in Table, depend on Name column in such a way that if AA or BB in column then in Category column must paste Duke, for CC category should be Mike, for DD or EE category should be Mark and so on. In the End I should get a Table

Name      Value        Category
AA          0           Duke    
BB          1           Duke    
CC          0           Mike
DD          1           Mark    
EE          1           Mark    
FF          1           Tom 
GG          0           Hex
HH          1           Tom

Table is quite big and impossible to make it manually so is there any smart way to read Name column and paste in Category column? Any loop function or combination of loop and paste function in r ? I search on stackoverflow but couldn't find a similar case. What I was thinking is something like this: Table$Category <- within(Table,ifelse(Name=="AA" | Name== "BB",paste("Duke")), ifelse (Name=="CC" ,paste("Mike")), ifesle(Name=="DD" | Name== "EE",paste("Mark")) Can someone have a look over this? Thank you.

Upvotes: 0

Views: 861

Answers (2)

akrun
akrun

Reputation: 887213

We can use a keyVal data.frame and then left_join

library(dplyr)
 keyVal <- structure(list(Name = structure(1:8, .Label = c("AA", "BB", "CC", 
  "DD", "EE", "FF", "GG", "HH"), class = "factor"), Category = structure(c(1L, 
 1L, 4L, 3L, 3L, 5L, 2L, 5L), .Label = c("Duke", "Hex", "Mark", 
  "Mike", "Tom"), class = "factor")), class = "data.frame",
  row.names = c(NA, -8L))


library(dplyr)
left_join(df1, keyVal)
#  Name Value Category
#1   AA     0     Duke
#2   BB     1     Duke
#3   CC     0     Mike
#4   DD     1     Mark
#5   EE     1     Mark
#6   FF     1      Tom
#7   GG     0      Hex
#8   HH     1      Tom

data

df1 <- structure(list(Name = structure(1:8, .Label = c("AA", "BB", "CC", 
 "DD", "EE", "FF", "GG", "HH"), class = "factor"), Value = c(0L, 
 1L, 0L, 1L, 1L, 1L, 0L, 1L)), class = "data.frame", row.names = c(NA, 
 -8L))

Upvotes: 0

s_baldur
s_baldur

Reputation: 33488

You could use a named vector where you define the mapping. Example:

lookup_vector <- c(
  AA = "Duke",
  BB = "Duke",
  CC = "Mike",
  DD = "Mark",
  EE = "Mark",
  FF = "Tom",
  GG = "Hex",
  HH = "Tom"
)

Table[["Category"]] <- lookup_vector[Table[["Name"]]]

#   Name Value Category
# 1   AA     0     Duke
# 2   BB     1     Duke
# 3   CC     0     Mike
# 4   DD     1     Mark
# 5   EE     1     Mark
# 6   FF     1      Tom
# 7   GG     0      Hex
# 8   HH     1      Tom

Data:

Table <- data.frame(
  Name = c("AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH"), 
  Value = c(0L, 1L, 0L, 1L, 1L, 1L, 0L, 1L)
)

Upvotes: 1

Related Questions