2

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)
0

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.