Renaming duplicate strings in R

前端 未结 4 1667
情歌与酒
情歌与酒 2021-01-14 17:31

I have an R dataframe that has two columns of strings. In one of the columns (say, Column1) there are duplicate values. I need to relabel that column so that it would have t

4条回答
  •  旧巷少年郎
    2021-01-14 18:01

    d <- read.table(text='Column1   Column2  
     1         A 
     1         B 
     2         C 
     2         D 
     3         E 
     4         F', header=TRUE)
    
    transform(d, 
        Column1.new = ifelse(duplicated(Column1) | duplicated(Column1, fromLast=TRUE), 
                             paste(Column1, ave(Column1, Column1, FUN=seq_along), sep='_'), 
                             Column1))
    
    #   Column1 Column2 Column1.new
    # 1       1       A         1_1
    # 2       1       B         1_2
    # 3       2       C         2_1
    # 4       2       D         2_2
    # 5       3       E           3
    # 6       4       F           4
    

提交回复
热议问题