R 中的数字列名 [英] numeric column names in R
问题描述
我有一个如下的数据框:
I have a data frame as follows:
structure(list(`104` = c(NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, "yes", NA, NA, NA, NA), `15` = c(NA,
NA, NA, NA, ">= 4.0", ">= 4.0", NA, "~ 2", "~ 2", "~ 2", "~ 2",
"~ 2", "~ 2", "< 2.2", "~2.75", NA, "~2.75", "~2.75", "~2.75",
"~2.75")), .Names = c("104", "15"), row.names = 45:64, class = "data.frame")
我知道使用数字列名不是最佳做法,但在这种情况下是必要的.我一直在通过检索带有反引号的列来操作我的数据框 `
I know that it is not best practices to have numeric column names, however it is necessary in this circumstance. I have been manipulating my data frame through retrieving columns with a backtick `
不幸的是,我在上面的数据框中发现了一些有趣的东西.
Unfortunately, I found something funny in the above data frame.
> table(testtest$`10`)
yes
1
>
但是没有列名称为10,所以看起来是在检索
However there is no column with a name of 10, so it looks like it is retrieving
> table(testtest$`104`)
yes
1
>
我现在很紧张,不相信这会在我不知道其他列(例如 41
和 4100
)的情况下再次弹出.
I am nervous now, and do not trust that this may pop up again without my knowing for other columns such as 41
and 4100
.
任何解释都会有帮助!谢谢
Any explanation would be helpful! Thanks
推荐答案
这是由于部分匹配.为避免这种情况,请使用 [[
提取列
This is due to the partial matching. To avoid it, use [[
to extract the columns
testtest[["10"]]
#NULL
而正确的列名给出输出
testtest[["104"]]
#[1] NA NA NA NA NA NA NA NA NA NA NA
#[12] NA NA NA NA "yes" NA NA NA NA
根据?"$"
[[ 和 $ 都选择列表中的单个元素.主要区别是 $ 不允许计算索引,而 [[ 允许.x$name 是等价于 x[["name", exact = FALSE]].此外,部分匹配[[ 的行为可以使用精确参数进行控制.
Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument.
<小时>
一般来说,最好不要有数字列名或以数字开头的名称.我们可以使用方便的函数 make.names
names(testtest) <- make.names(names(testtest))
names(testtest)
#[1] "X104" "X15"
这篇关于R 中的数字列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!