重命名通过R中名称外观的位置重复行名称和索引

时间:2017-12-20 06:59:45

标签: r

我有一个数据表,其中包含变量Top,我将Top变量视为我的行名,因为您可以看到第一个表的行名称是重复的,所以我想为行名称添加索引,如基于子索引关于事件的位置。

First table
row Top points  
IS  IS  3   
HT  HT  S   
ON2 ON2 837 
IS  IS  19  
NO  NO  41  
IS  IS  IC  
ON2 ON2 40  
HT  HT  1   
ON2 ON2 BI  

Expected - If I want to see the row name ON2_1 it has appeared in three places and I have to index them based on the position they appeared. 

output
rowname occured Top  points
IS_1    1ST    TIME  IS 
HT_1    1ST    TIME  HT 
ON2_1   1ST    TIME  ON2
IS_2    2ND    TIME  IS 
NO_1    1ST    TIME  NO 
IS_3    3RD    TIME  IS 
ON2_2   2ND    TIME  ON2    
HT_2    2ND    TIME  HT 
ON2_3   3RD    TIME  ON2

1 个答案:

答案 0 :(得分:1)

我们可以使用

library(dplyr)    
df1 %>%
     group_by(Top) %>% 
     mutate(rn = row_number()) %>%
     transmute(rowname = paste(row, rn , sep="_"), 
              occured = c("1ST", "2ND", "3RD")[rn], 
              points = row) %>% 
     ungroup %>%
     mutate(Top = "TIME")