我有一个数据帧(df),它的列(c1)看起来像这样:
c1
AA
AA
BB
BB
CC
CC
DD
DD
我想要这样的输出
c1
AA_1
AA_2
BB_1
BB_2
CC_1
CC_2
DD_1
DD_2
我现在有一个代码可以向所有行添加特定模式:
strsplit(paste(df$c1, collapse='_1 '), ' ')[[1]]
但是,如何将模式“ _1”添加到所有奇数行,将模式“ _2”添加到所有偶数行?
高度赞赏的任何帮助
答案 0 :(得分:2)
尝试:
df$ID=c(1:nrow(df))
df$New_C1<-ifelse(df$ID%%2!=0,paste0(df$c1,"_1"),paste0(df$c1,"_2"))
df
或者,如果您需要覆盖,则:
df$ID=c(1:nrow(df))
df$c1<-ifelse(df$ID%%2!=0,paste0(df$c1,"_1"),paste0(df$c1,"_2"))
df$ID<-NULL
结果:
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
答案 1 :(得分:1)
这是一个dplyr
解决方案。
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
这是@RonakShah提供的基本方式:
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)
答案 2 :(得分:1)
为了安全起见并处理条目数不为偶数的情况,您可以执行以下操作:
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