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
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"
df1 <- structure(list(Letter = c("A", "B", "C", "B", "B", "A")),
class = "data.frame", row.names = c(NA,
-6L))
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.