抱歉,如果这是微不足道的。我在 R 中看到以下行为:
> myDF <- data.frame(Score=5, scoreScaled=1)
> myDF$score ## forgot that the Score variable was capitalized
[1] 1
预期结果:返回 NULL(更好:抛出错误)。
我已经搜索过此内容,但找不到任何有关此行为的讨论。有谁能够提供有关此问题的任何参考资料、这样做的理由以及是否有任何方法可以防止这种情况发生?一般来说,我会喜欢一个对其变量更严格的 R 版本,但似乎永远不会发生......
$
运算符只需要数据帧名称的第一个唯一部分即可对其进行索引。例如:
> d <- data.frame(score=1, scotch=2)
> d$sco
NULL
> d$scor
[1] 1
避免这种行为的一种方法是使用 [[]] 运算符,其行为如下:
> d <- data.frame(score=1, scotch=2)
> d[['scor']]
NULL
> d[['score']]
[1] 1
我希望这对你有帮助。
干杯!
使用
[,""]
而不是 $
将在找不到名称的情况下抛出错误。
myDF$score
#[1] 1
myDF[,"score"]
#Error in `[.data.frame`(myDF, , "score") : undefined columns selected
myDF[,"Score"]
#[1] 5
myDF[,"score", drop=TRUE] #More explicit and will also work with tibble::as_tibble
#Error in `[.data.frame`(myDF, , "score", drop = TRUE) :
# undefined columns selected
myDF[,"Score", drop=TRUE]
#[1] 5
as.data.frame(myDF)[,"score"] #Will work also with tibble::as_tibble and data.table::as.data.table
#Error in `[.data.frame`(as.data.frame(myDF), , "score") :
# undefined columns selected
as.data.frame(myDF)[,"Score"]
#[1] 5
unlist(myDF[,"score"], use.names = FALSE) #Will work also with tibble::as_tibble and data.table::as.data.table
#Error in `[.data.frame`(myDF, , "score") : undefined columns selected
unlist(myDF[,"Score"], use.names = FALSE)
#[1] 5