【问题标题】:Test whether data is numeric or Factor/Ordinal测试数据是数字还是因子/序数
【发布时间】:2014-04-23 10:16:52
【问题描述】:

我正在处理一个大型数据集,想要获取有关我的变量的一些基本信息,首先是它们是数字还是因子/序数。

我正在使用一个函数,并且想要一次一个变量,调查它是数字还是因子。

为了使 for 循环正常工作,我使用 dataset[i] 来获取我想要的变量。

object<-function(dataset){

    n=ncol(dataset)
    for(i in 1:n){
       variable_name<-names(dataset[i])
       factor<-is.factor(dataset[i])
       rdered<-is.ordered(dataset[i])
       numeric<-is.numeric(dataset[i])
       print(list(variable_name,factor,ordered,numeric))
    }
}

是有序的 我的问题是 is.numeric() 似乎不适用于 dataset[i],所有结果都变为“FALSE”,但仅适用于 dataset$。

你知道如何解决这个问题吗?

【问题讨论】:

  • dataset的类型是什么? data.frame?

标签: r types


【解决方案1】:

尝试str(dataset) 获取有关对象的摘要信息,但要解决您的问题,您需要使用双方括号完全提取数据。单方括号子集将输出保留为子列表(或 data.frame),而不是提取内容:

str(iris)
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
is.numeric(iris[1])
[1] FALSE
class(iris[1])
[1] "data.frame"
is.numeric(iris[[1]])
[1] TRUE

【讨论】:

  • @user20650 你说得对,我会删除那句话。它们是引擎盖下的数字(整数),但 is.numeric 并没有意识到这一点。
【解决方案2】:

假设dataset 类似于data.frame,您可以执行以下操作(并避免循环):

names = sapply(dataset, names) # or simply `colnames(dataset)`
types = sapply(dataset, class)

然后types 给你numericfactor。然后你可以简单地做这样的事情:

is_factor = types == 'factor'

【讨论】:

    猜你喜欢
    • 2014-10-01
    • 1970-01-01
    • 2014-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多