奇怪的行为从R中的data.frame中删除列 [英] Strange behaviour dropping column from data.frame in R

查看:185
本文介绍了奇怪的行为从R中的data.frame中删除列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从data.frame中删除列时,我遇到了一个奇怪的行为。最初我有:

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

现在,我从data.frame中删除 a $ a

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

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

如预期的那样,我的data.frame中只有 abc 列。但奇怪的部分开始,当我尝试引用删除的列 a

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

像R返回值 a $ abc 而不是 NULL

当剩余列的名称的开头与已删除的列的名称完全一致时,会发生这种情况。

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

这是一个错误,还是我错过了这里? / p>

Is it a bug or do I miss something here?

推荐答案

虽然您的确切问题已经在评论中得到回答,但是避免此行为的另一种方法是将您的 data.frame tibble ,这是一个被删除的版本的 data.frame 列名称为munging 的$ c> >其他事情:

While your exact question has already been answered in the comments, an alternative to avoid this behaviour is to convert your data.frame to a tibble, which is a stripped downed version of a data.frame, without column name munging, among other things:

library(tibble)
df_t <- as_data_frame(a)
df_t
# A tibble: 3 × 1
    abc
  <dbl>
1     3
2     2
3     1
> df_t$a
NULL
Warning message:
Unknown column 'a' 

这篇关于奇怪的行为从R中的data.frame中删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆