gpt4 book ai didi

r - R中的级别是什么?

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

我知道这是一个非常基本的问题,但我不明白 R 中的级别是什么意思。

作为引用,我做了一个简单的脚本来读取 CSV 表,过滤其中一个字段,将其传递给一个新变量并清除为第一个变量分配的内存。如果我在过滤的字段上调用 ​​unique() ,我会看到结果确实被过滤了,但还有一行显示与原始数据集中的数据相对应的“级别”。

例子:

df = read.csv(path, sep=",", header=TRUE)
df_intrate = df[df$AssetClass == "ASSET CLASS A", ]

rm(df)
gc()

unique(df_intrate$AssetClass)

结果:
[1] ASSET CLASS A
Levels: ASSET CLASS E ASSET CLASS D ASSET CLASS C ASSET CLASS B ASSET CLASS A

是来自 df的结构信息尽管 R studio 显示 df_intrate 确实是 ASSET CLASS A 的预期行数,但仍以某种方式保留在 df_intrate 中?

最佳答案

Is the structural information from df somehow preserved in df_intrate despite R studio showing that df_intrate is indeed the expected number of rows for ASSET CLASS A ?



是的。这就是分类变量(称为因子)存储在 R 中的方式 - 存储水平、所有可能值的向量和所取的实际值:
x = factor(c('a', 'b', 'c', 'a', 'b', 'b'))
x
# [1] a b c a b b
# Levels: a b c

y = x[1]
# [1] a
# Levels: a b c

您可以使用 droplevels() 删除未使用的级别,或通过重新应用 factor函数,仅从现有的东西中创建一个新的因素:
droplevels(y)
# [1] a
# Levels: a

factor(y)
# [1] a
# Levels: a

您也可以使用 droplevels在数据框中删除所有因子列中所有未使用的级别:
dat = data.frame(x = x)
str(dat)
# 'data.frame': 6 obs. of 1 variable:
# $ x: Factor w/ 3 levels "a","b","c": 1 2 3 1 2 2

str(dat[1, ])
# Factor w/ 3 levels "a","b","c": 1

str(droplevels(dat[1, ]))
# Factor w/ 1 level "a": 1

虽然与您当前的问题无关,但我们也应该提到 factor有一个可选的 levels参数,可用于指定因子的级别以及它们应该采用的顺序。如果您想要一个特定的顺序(可能用于绘图或建模),或者如果可能的级别比实际存在的级别更多并且您想要包括它们,这会很有用。如果不指定 levels ,默认将按字母顺序排列。
x = c("agree", "disagree", "agree", "neutral", "strongly agree")
factor(x)
# [1] agree disagree agree neutral strongly agree
# Levels: agree disagree neutral strongly agree
## not a good order

factor(x, levels = c("disagree", "neutral", "agree", "strongly agree"))
# [1] agree disagree agree neutral strongly agree
# Levels: disagree neutral agree strongly agree
## better order

factor(x, levels = c("strongly disagree", "disagree", "neutral", "agree", "strongly agree"))
# [1] agree disagree agree neutral strongly agree
# Levels: strongly disagree disagree neutral agree strongly agree
## good order, more levels than are actually present

您可以使用 ?reorder?relevel (或再次 factor)更改已创建因子的级别顺序。

关于r - R中的级别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46830939/

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