使具有重复值的列在数据框中唯一 [英] 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'))
我可以通过
unique(employee$name)
但是,我想将其中的每个项目名称
列唯一。如果第二次出现某些内容,请在其后附加_1。如果再次出现,请在其后附加_2。因此,在员工数据框中,我想将第二列更改为
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?
推荐答案
我们可以将 make.names
与一起使用= TRUE
。默认情况下,。
将附加在后缀数字之前,并且可以使用<$ c替换为 _
$ c> sub
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))
或者建议使用更好的选择通过@DavidArenburg。如果名称
列是 factor
类,则将输入列转换为字符
类(<。code> as.character ),然后再应用
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"
这篇关于使具有重复值的列在数据框中唯一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!