[,]和$之间的逻辑语句的差异 [英] Difference in Logical Statement between [,] and $

查看:80
本文介绍了[,]和$之间的逻辑语句的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个具有两列客户ID('Custid')和收入('Income')的数据框('df_temp'):

I am working on a data frame ('df_temp') with two columns customer id ('Custid') and income ('Income'):

  Custid    Income
  <fctr>     <dbl>
1   1003  29761.20
2   1004  98249.55
3   1006  23505.30
4   1007  72959.25
5   1009 114973.95
6   1010  25038.30

在检查收入是否为数字时,我面临以下问题:

While checking if Income is numeric, I am facing the following problem:

使用$引用收入,返回TRUE:

Using $ to refer to Income, returns TRUE:

> is.numeric(df_temp$Income)
[1] TRUE

使用[,2]或[,which(...)]引用收入,返回FALSE:

Using [,2] or [,which(...)] to refer to Income, returns FALSE:

> i <- which(names(df_temp)=='Income')
> is.numeric(df_temp[,i])
[1] FALSE
> is.numeric(df_temp[,2])
[1] FALSE

当尝试使用[,]将此向量设置为数值时,我遇到了另一个问题:

When trying to set this vector to numerical using [,], I run into another issue:

> df_temp[,2] <- as.numeric(df_temp[,2])

Error: (list) object cannot be coerced to type 'double'

我一直认为$和[]在引用数据帧中的向量时起着相同的作用.

I always thought that $ and [] serve the same purpose when referring to a vector in a data frame.

有人可以帮助我理解问题,并使用[,]表达式将此向量转换为数值吗?

Could somebody please help me understanding the problem and converting this vector into numerical, using the [,] expression?

推荐答案

您不使用data.frame.您正在使用"tbl_df".使用$子集tbl_df返回向量.使用[子集tbl_df返回tbl_df,而tbl_df不是数字矢量,因此is.numeric返回FALSE.

You're not working with a data.frame. You're working with a "tbl_df". Subsetting a tbl_df using $ returns a vector. Subsetting a tbl_df using [ returns a tbl_df, and a tbl_df is not a numeric vector, so is.numeric returns FALSE.

tbl_df所做的一件事是在调用[时使用drop = FALSE.但是,通过主动阻止您设置drop = TRUE:

One thing tbl_df does is uses drop = FALSE when calling [. But it goes even further by actively preventing you from setting drop = TRUE:

x <- tbl_df(mtcars)
is.numeric(x[,"cyl",drop=TRUE])
# [1] FALSE
Warning messages:
1: drop ignored 

因此,您不能以所需的方式将[与tbl_df一起使用.您必须使用$[[提取向量.

So, you cannot use [ with a tbl_df in the way you want. You have to use $ or [[ to extract the vector.

is.numeric(x$cyl)
# [1] TRUE
is.numeric(x[["cyl"]])
# [1] TRUE

这篇关于[,]和$之间的逻辑语句的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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