Reputation: 725
I have a data frame (df) which has a column (c1) which looks like this:
c1
AA
AA
BB
BB
CC
CC
DD
DD
I would like to have such an output
c1
AA_1
AA_2
BB_1
BB_2
CC_1
CC_2
DD_1
DD_2
I have a code right now to add a specific pattern to all the rows:
strsplit(paste(df$c1, collapse='_1 '), ' ')[[1]]
However, how can I add the pattern "_1" to all the odd rows and the pattern "_2" to all the even rows?
Any help highly appreciated
Upvotes: 1
Views: 368
Reputation: 1445
to be on the safe side and handle cases where there not be an even number of entries, you can do the following:
library(tidyverse)
# define data; has some 'odd' cases
df <- data.frame(c1 = c("AA", "AA", "BB", "BB", "CC", "CC", "DD", "DD", "DD", "EE"),
stringsAsFactors = FALSE
)
# split the data by 'c1' and then add a suffix based on the number of entries
result <- df %>%
group_by(c1) %>%
mutate(new_C1 = paste0(c1, "_", seq(n())))
> result
# A tibble: 10 x 2
# Groups: c1 [5]
c1 new_C1
<chr> <chr>
1 AA AA_1
2 AA AA_2
3 BB BB_1
4 BB BB_2
5 CC CC_1
6 CC CC_2
7 DD DD_1
8 DD DD_2
9 DD DD_3
10 EE EE_1
Upvotes: 1
Reputation: 35604
This is a dplyr
solution.
df %>% mutate(c2 = paste(c1, 1:2, sep = "_"))
c1 c2
1 AA AA_1
2 AA AA_2
3 BB BB_1
4 BB BB_2
5 CC CC_1
6 CC CC_2
Here is base way @RonakShah provide:
with(df, paste(c1, 1:2, sep = "_"))
# [1] "AA_1" "AA_2" "BB_1" "BB_2" "CC_1" "CC_2"
# data
df <- data.frame(c1 = c("AA", "AA", "BB", "BB", "CC", "CC"), stringsAsFactors = F)
Upvotes: 1
Reputation: 13319
Try:
df$ID=c(1:nrow(df))
df$New_C1<-ifelse(df$ID%%2!=0,paste0(df$c1,"_1"),paste0(df$c1,"_2"))
df
Or if you need to overwrite, then:
df$ID=c(1:nrow(df))
df$c1<-ifelse(df$ID%%2!=0,paste0(df$c1,"_1"),paste0(df$c1,"_2"))
df$ID<-NULL
Result:
c1
1 AA_1
2 AA_2
3 BB_1
4 BB_2
5 CC_1
6 CC_2
7 DD_1
8 DD_2
Upvotes: 2