R:为什么我没有得到类型或类的“因素"?将列转换为因子后? [英] R: Why am I not getting type or class "factor" after converting columns to factor?

查看:17
本文介绍了R:为什么我没有得到类型或类的“因素"?将列转换为因子后?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下设置.

df <- data.frame(aa = rnorm(1000), bb = rnorm(1000))

apply(df, 2, typeof)
#      aa       bb 
#"double" "double" 

apply(df, 2, class)
#       aa        bb 
#"numeric" "numeric" 

然后我尝试将其中一列转换为因子".但是正如你在下面看到的,我没有得到任何因子"类型或类.我做错了什么吗?

Then I try to convert one of the columns to "factor". But as you can see below, I am not getting any "factor" type or classes. Am I doing anything wrong ?

df[, 1] <- as.factor(df[, 1])

apply(df, 2, typeof)
#         aa          bb 
#"character" "character" 

apply(df, 2, class)
#         aa          bb 
#"character" "character" 

推荐答案

抱歉,我觉得我原来的答案写得不好.为什么我一开始就把那个因素矩阵"放进去?这是一个更好的尝试.

Sorry I felt my original answer badly written. Why did I put that "matrix of factors" in the very beginning? Here is a better try.

来自 ?apply:

 If ‘X’ is not an array but an object of a class with a non-null
 ‘dim’ value (such as a data frame), ‘apply’ attempts to coerce it
 to an array via ‘as.matrix’ if it is two-dimensional (e.g., a data
 frame) or via ‘as.array’.

因此,在按行或按列应用 FUN 之前,数据帧由 as.matrix 转换为矩阵.

So a data frame is converted to a matrix by as.matrix, before FUN is applied row-wise or column-wise.

来自?as.matrix:

 ‘as.matrix’ is a generic function.  The method for data frames
 will return a character matrix if there is only atomic columns and
 any non-(numeric/logical/complex) column, applying ‘as.vector’ to
 factors and ‘format’ to other non-character columns.  Otherwise,
 the usual coercion hierarchy (logical < integer < double <
 complex) will be used, e.g., all-logical data frames will be
 coerced to a logical matrix, mixed logical-integer will give a
 integer matrix, etc.

 The default method for ‘as.matrix’ calls ‘as.vector(x)’, and hence
 e.g. coerces factors to character vectors.

我的母语不是英语,我无法阅读以下内容(这看起来很重要!).有人可以澄清一下吗?

I am not a native English speaker and I can't read the following (which looks rather important!). Can someone clarify it?

如果只有原子列和任何非(数字/逻辑/复数)列,数据帧的方法将返回字符矩阵,将as.vector"应用于因子,将格式"应用于其他非字符列.

The method for data frames will return a character matrix if there is only atomic columns and any non-(numeric/logical/complex) column, applying ‘as.vector’ to factors and ‘format’ to other non-character columns.

来自?as.vector:

 Note that factors are _not_ vectors; ‘is.vector’ returns ‘FALSE’
 and ‘as.vector’ converts a factor to a character vector for ‘mode
 = "any"’.

简单地说,只要你在数据框中有一个因子列,as.matrix 就会给你一个字符矩阵.

Simply put, as long as you have a factor column in a data frame, as.matrix gives you a character matrix.

我相信这个带有数据框问题的 apply 已经被多次提出,上面只是添加了另一个重复的答案.真对不起.我没有仔细阅读OP的问题.首先让我感到震惊的是,R 无法构建真正的因子矩阵.

I believed this apply with data frame problem has been raised many times and the above just adds another duplicate answer. Really sorry. I failed to read OP's question carefully. What hit me in the first instance is that R can not build a true matrix of factors.

f <- factor(letters[1:4])

matrix(f, 2, 2)
#     [,1] [,2]
#[1,] "a"  "c" 
#[2,] "b"  "d" 

## a sneaky way to get a matrix of factors by setting `dim` attribute
dim(f) <- c(2, 2)
#     [,1] [,2]
#[1,] a    c   
#[2,] b    d   
#Levels: a b c d

is.matrix(f)
#[1] TRUE

class(f)
#[1] "factor"  ## not a true matrix with "matrix" class

虽然这很有趣,但它应该与 OP 的问题不太相关.

While this is interesting, it should be less-relevant to OP's question.

再次抱歉把这里弄得一团糟.好惨!!

Sorry again for making a mess here. So bad!!

那么,如果我使用 sapply 会有帮助吗?因为我有很多列需​​要转换为因子.

So if I do sapply would it help? Because I have many columns that need to be converted to factor.

实际使用lapply.sapply 将结果简化为一个数组,它是二维情况下的矩阵.下面是一个例子:

Use lapply actually. sapply would simplify the result to an array, which is a matrix in 2D case. Here is an example:

dat <- head(trees)
sapply(dat, as.factor)
#     Girth  Height Volume
#[1,] "8.3"  "70"   "10.3"
#[2,] "8.6"  "65"   "10.3"
#[3,] "8.8"  "63"   "10.2"
#[4,] "10.5" "72"   "16.4"
#[5,] "10.7" "81"   "18.8"
#[6,] "10.8" "83"   "19.7"

new_dat <- data.frame(lapply(dat, as.factor))
str(new_dat)
#'data.frame':  6 obs. of  3 variables:
# $ Girth : Factor w/ 6 levels "8.3","8.6","8.8",..: 1 2 3 4 5 6
# $ Height: Factor w/ 6 levels "63","65","70",..: 3 2 1 4 5 6
# $ Volume: Factor w/ 5 levels "10.2","10.3",..: 2 2 1 3 4 5

sapply(new_dat, class)
#   Girth   Height   Volume 
#"factor" "factor" "factor" 

apply(new_dat, 2, class)
#      Girth      Height      Volume 
#"character" "character" "character" 

关于typeof,因子实际上存储为整数.

Regarding typeof, factors are actually stored as integers.

sapply(new_dat, typeof)
#    Girth    Height    Volume 
#"integer" "integer" "integer" 

当您 dput 一个因素时,您可以看到这一点.例如:

When you dput a factor you can see this. For example:

dput(new_dat[[1]])
#structure(1:6, .Label = c("8.3", "8.6", "8.8", "10.5", "10.7", 
#"10.8"), class = "factor")

实际值为1:6.人物等级只是一个属性.

The real values are 1:6. Character levels are just an attribute.

这篇关于R:为什么我没有得到类型或类的“因素"?将列转换为因子后?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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