1

I would like to ask you the following in R: I have one column: Letter= A, B, C, B, B, A and i want to have a new column, where it looks like this: Letter = A4, B2, C1, B2, B2, A4 . So each time is A, I add the 4, for B the 2 and for C the 1 number in the end.

thank you in advance! Eleni

neilfws
  • 32,751
  • 5
  • 50
  • 63
Eleni
  • 15
  • 3
  • It would be easier to help if you create a small reproducible example along with expected output. Read about [how to give a reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Feb 05 '21 at 07:28

2 Answers2

2

Create a key/value named vector and use that to match and replace values based on the 'Letter' column, paste that output with the 'Letter' column

mapping_vec <- setNames(c(4, 2, 1), c("A", "B", "C"))
df1$newCol <- with(df1, paste0(Letter, mapping_vec[Letter]))
df1$newCol
#[1] "A4" "B2" "C1" "B2" "B2" "A4"

data

df1 <- structure(list(Letter = c("A", "B", "C", "B", "B", "A")), 
class = "data.frame", row.names = c(NA, 
-6L))
akrun
  • 874,273
  • 37
  • 540
  • 662
2

An option with match

transform(
  df,
  NewCol = paste0(Letter, c(4, 2, 1)[match(Letter, c("A", "B", "C"))])
)

gives

  Letter NewCol
1      A     A4
2      B     B2
3      C     C1
4      B     B2
5      B     B2
6      A     A4

Data

df <- data.frame(Letter = c("A", "B", "C", "B", "B", "A"))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81