gpt4 book ai didi

r - R 如何知道来自给定数据帧的哪种数据要考虑为一个因素?

转载 作者:行者123 更新时间:2023-12-04 18:18:46 25 4
gpt4 key购买 nike

关闭。这个问题需要debugging details .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

2年前关闭。




Improve this question




考虑到 Kaggle ( https://www.kaggle.com/c/titanic/data ) 上可用的泰坦尼克号数据集的给定数据,我试图找出 R 上每一列的数据类型。它返回乘客姓名、性别和票号的因子数据类型.它返回年龄的数字数据类型。为什么不将年龄列表视为整数甚至因子?年龄确实在数据集中重复出现。不能说是不同的层次吗?

我用了 str()函数返回 R 中的数据类型。

str(test.survived)
$ Age : num 34.5 47 62 27 22 14 30 26 18 21 ...
$ Ticket : Factor w/ 363 levels "110469","110489",..: 153 222 74 148 139 262 159 85 101 270 ...

.
str(test.survived)

输出:
    'data.frame':   418 obs. of  12 variables:
$ survived : Factor w/ 1 level "None": 1 1 1 1 1 1 1 1 1 1 ...
$ PassengerId: int 892 893 894 895 896 897 898 899 900 901 ...
$ Pclass : int 3 3 2 3 3 3 3 2 3 3 ...
$ Name : Factor w/ 418 levels "Abbott, Master. Eugene Joseph",..: 210
409 273 414 182 370 85 58 5 104 ...
$ Sex : Factor w/ 2 levels "female","male": 2 1 2 2 1 2 1 2 1 2 ...
$ Age : num 34.5 47 62 27 22 14 30 26 18 21 ...
$ SibSp : int 0 1 0 0 1 0 0 1 0 2 ...
$ Parch : int 0 0 0 0 1 0 0 1 0 0 ...
$ Ticket : Factor w/ 363 levels "110469","110489",..: 153 222 74 148 139
262 159 85 101 270 ...
$ Fare : num 7.83 7 9.69 8.66 12.29 ...
$ Cabin : Factor w/ 77 levels "","A11","A18",..: 1 1 1 1 1 1 1 1 1 1
...
$ Embarked : Factor w/ 3 levels "C","Q","S": 2 3 2 3 3 3 2 3 1 3 ...

据我所知,因子用于具有重复值的数据集,因此将它们分类为级别。就像票号,机舱类型一样,年龄也有重复。但是 R 不认为年龄是一个因素,而是为其分配了一个数字数据类型。我知道它不能是整数类型,因为那里有一些 float 数据值。但为什么不考虑因素?

最佳答案

读取的数据取决于您使用的函数以及您指定的任何参数。

如果你使用了类似 read.csv() 的东西,然后使用函数 type.convert()为每一列设置数据类型。来自 notes :

Given a vector, the function attempts to convert it to logical, integer, numeric or complex, and failing that converts a character vector to factor unless as.is = TRUE. The first type that can accept all the non-missing values is chosen.



该函数按照该顺序遍历类类型以确定列应该是什么。因此,只有在无法分配数字类别时才会使用因子类型。在这种情况下,它是一个数字列。

更多信息

通常,人们不希望他们的字符列作为因子被读入。为避免这种情况,请使用 stringsAsFactors = FALSE在 csv 中阅读时。

如果您希望数字列成为因子,则可以使用
test.survived$Age <- as.factor(test.survived$Age)

例如。

关于r - R 如何知道来自给定数据帧的哪种数据要考虑为一个因素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56444855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com