Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - Make a column with duplicated values unique in a dataframe

I have a dataframe where a column has duplicate values like

employee <- data.frame(name = c('John', 'Joe', 'Mat', 'John', 'Joe'), 
            salary = c(1500, 2000, 1700, 1210, 2100), 
            startdate = c('2012-05-10', '2015-02-17', 
            '2014-09-11', '2011-11-23', '2010-10-27'))

I can get the unique elements in column 1 by

unique(employee$name)

However, I want to make each items in the name column unique. If something appears second time append _1 to it. If it appears again append _2 to it. So, in the employee dataframe, I want to change the second column to

John
Joe
Mat
John_1
Joe_1

Is there a way except looping over it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We can use make.names with unique=TRUE. By default, a . will be appended before the suffix numbers, and that can be replaced by _ using sub

 employee$name <- sub('[.]', '_', make.names(employee$name, unique=TRUE))

Or a better option suggested by @DavidArenburg. If the name column is factor class, convert the input column to character class (as.character) before applying the make.unique

 make.unique(as.character(employee$name), sep = "_")
 #[1] "John"   "Joe"    "Mat"    "John_1" "Joe_1" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...