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
609 views
in Technique[技术] by (71.8m points)

dataframe - Strange behaviour dropping column from data.frame in R

I've encountered a strange behavior when dropping columns from data.frame. Initially I have:

> a <- data.frame("a" = c(1,2,3), "abc" = c(3,2,1)); print(a)
  a abc
1 1   3
2 2   2
3 3   1

Now, I remove a$a from the data.frame

> a$a <- NULL; print(a)
  abc
1   3
2   2
3   1

As expected, I have only abc column in my data.frame. But the strange part begins, when I try to reference deleted column a.

> print(a$a)
[1] 3 2 1
> print(is.null(a$a))
[1] FALSE

It looks like R returns value of the a$abc instead of NULL.

This happens when the beginning of the name of remaining column exactly matches the name of deleted column.

Is it a bug or do I miss something here?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

From the the help. ?$

name: A literal character string or a name (possibly backtick quoted). For extraction, this is normally (see under ‘Environments’) partially matched to the names of the object.

So that's the normal behaviour because the name is partially matched. See ?pmatch for more info about partial matching.

Cheers


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

...