Conditional string concatenate

Viewed 181

I have this type of DF

DF
ID V1
1  A
2  V
3  C
4  B
5  L
6  L

I would like to get

ID V1  V2
1  A   AA
2  V   AV
3  C   AC
4  B   BB
5  L   BL
6  L   BL

I would like to concatenate A, B in V1 with other characters in V1.

I used something like this

DF%>%
mutate(V2 = ifelse ((V1 == "A" ), paste ("A", ID), ifelse ((V1 == "B")), paste ("B",V1),   "")%>%
V2 = na_if (V2, ""))%>%
fill (V2)
3 Answers

Here is a way using base R

df <- transform(df,
                V2 = ave(x = V1,
                         cumsum(V1 %in% c("A", "B")), #grouping variable
                         FUN = function(x) paste0(x[1], x)))

Gives

df
#  ID V1 V2
#1  1  A AA
#2  2  V AV
#3  3  C AC
#4  4  B BB
#5  5  L BL
#6  6  L BL

You can use %in% to find where A and B is. Use unsplit to replicate them and paste0 to make the new string.

i <- DF$V1 %in% c("A", "B")
DF$V2 <- paste0(unsplit(DF$V1[i], cumsum(i)), DF$V1)
#DF$V2 <- paste0(rep(DF$V1[i], diff(c(which(i), length(i)))), DF$V1) #Alternative
DF
#  ID V1 V2
#1  1  A AA
#2  2  V AV
#3  3  C AC
#4  4  B BB
#5  5  L BL
#6  6  L BL

Here is a dplyr solution.

library(dplyr)

DF %>%
  mutate(flag = cumsum(V1 %in% c("A", "B"))) %>%
  group_by(flag) %>%
  mutate(V2 = paste0(first(V1), V1)) %>%
  ungroup() %>%
  select(-flag)
## A tibble: 6 x 3
#     ID V1    V2   
#  <int> <chr> <chr>
#1     1 A     AA   
#2     2 V     AV   
#3     3 C     AC   
#4     4 B     BB   
#5     5 L     BL   
#6     6 L     BL
Related