我有一个包含重复列名的数据框。我知道使用重复的列名是不标准的,但这些名称实际上是使用用户输入在下游重新分配的。现在,我正在尝试按位置对数据框进行子集化,但列名已被删除重复。这是一个例子。
> df <- data.frame(x = 1:4, y = 2:5, y = LETTERS[2:5], y = (2+(2:5)), check.names = F)
> df
x y y y
1 1 2 B 4
2 2 3 C 5
3 3 4 D 6
4 4 5 E 7
但是,当我尝试子集化时,名称会改变...
> df[, 1:3]
x y y.1
1 1 2 B
2 2 3 C
3 3 4 D
4 4 5 E
有什么办法可以防止这种情况发生吗?它仅在我对列而非行进行子集化时发生。
> df[1:3,]
x y y y
1 1 2 B 4
2 2 3 C 5
3 3 4 D 6
为注意到此行为的其他人编辑:
我已经从 extract.data.frame (type ?'['
) 的帮助页面深入研究了行为和这个相关部分
相关部分指出:
If [ returns a data frame it will have unique (and non-missing) row names, if necessary transforming the row names using make.unique. Similarly, if columns are selected column names will be transformed to be unique if necessary (e.g., if columns are selected more than once, or if more than one column of a given name is selected if the data frame has duplicate column names).
这解释了原因,感谢到目前为止关于解决如何最好地解决这个问题的评论。
最佳答案
这是一个选项,尽管我认为重复列名不是一个好主意。
as.data.frame(as.list(df)[1:3], check.names = F)
# x y y
# 1 1 2 B
# 2 2 3 C
# 3 3 4 D
# 4 4 5 E
关于r - 子集化时数据框列名称不再唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47539438/