Home > OS >  Duplicate strings in R dataframe
Duplicate strings in R dataframe

Time:10-31

Is there a way to get desired output. I mean duplicating strings as per vectors

> df <- data.frame(a = c("A","B"))
> df$new <- ids::random_id(nrow(df), 4)
> df$cat <- c("X","Y")
> df$cat[df$a %in% c("A","A","B", "B")]
[1] "X" "Y"

Expected output (Repeating vectors since we are find in c("A","A","B", "B"))

[1] "X" "X" "Y" "Y"

CodePudding user response:

You could do that if your data frame had the respective rownames.

rownames(df) <- c('A', 'B')
df[c("A", "A", "B", "B"), 'cat']
# [1] "X" "X" "Y" "Y"
  •  Tags:  
  • r
  • Related