Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional string concatenate

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)
like image 598
onhalu Avatar asked Mar 28 '26 19:03

onhalu


2 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
like image 55
markus Avatar answered Mar 31 '26 10:03

markus


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
like image 32
GKi Avatar answered Mar 31 '26 10:03

GKi