访问因子的基础整数,而不是它们在R中的级别。

问题描述 投票:0回答:1

我经常把长文字的因素变量作为层次(如调查中的回答。"我非常同意这句话" 可以是一个级别)。) 如果我想基于因子变量进行子集,总是输入完整的级别是很烦人的。我更希望有一个从底层整数到级别的映射概览,并基于这个整数进行访问。

set.seed(1896)
df <- data.frame(y = runif(100, 0, 10000), x = factor(rep(c("I strongly agree", "I agree", "I disagree", "I strongly disagree"), 25)))
mean(df$y[df$x == "I strongly agree"])

通过访问底层整数可以得到同样的结果。

mean(df$y[as.integer(df$x) == 3])

我有两个相关的问题:1)有没有一种更bettersafer的方式来做这件事? 在有值和值标签的Stata中,可以直接访问标签或值,在R中是否存在类似的东西?2)有没有办法在R中快速看到一个从整数到因子级的映射表?一个命令,可以给我这样一个表:1--"我同意";2--"我不同意";3--"我非常同意";4--"我非常不同意"?

先谢谢你

r stata r-factor
1个回答
2
投票

对你的问题不是很清楚,因为我从来没有用过Stata。最重要的一步是因子部分。默认情况下,水平是按字母顺序排序的。

df = data.frame(y = runif(100, 0, 10000), x = rep(c("I strongly agree", "I agree", "I disagree", "I strongly disagree"), 25))

levels(df$x)
[1] "I agree"             "I disagree"          "I strongly agree"   
[4] "I strongly disagree"

为了安全起见,我猜你的意思是为每个数据集定义相同的级别。所以你可以这样做。

lvls = c("I strongly agree", "I agree", "I disagree", "I strongly disagree")
df$x = factor(df$x,levels=lvl)

levels(df$x)
[1] "I strongly agree"    "I agree"             "I disagree"         
[4] "I strongly disagree"

所以对于表格,也许可以这样做:

data.frame(num = 1:length(lvl),lvl)
  num                 lvl
1  1    I strongly agree
2  2             I agree
3  3          I disagree
4  4 I strongly disagree

你可以用子集

df[df$x==lvl[1],]

或者:

df[df$x==levels(df$x)[1],]
© www.soinside.com 2019 - 2024. All rights reserved.