Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
606 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 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...