R中的自动虚拟变量 [英] Automatic Dummy Variables in R

查看:183
本文介绍了R中的自动虚拟变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面创建了以下数据框:

I have the following data frame which is created below:

temp <- as.data.frame(with(uadm, table(prlo_state_code)))

我要创建11个虚拟变量。前十名中的每一个,其他中的一个。可以轻松找到前十名:

I am looking to create 11 dummy variables. One for each of the top 10 and an 'other'. The top 10 can easily be found with:

#top10
temp <- temp[order(temp$Freq, decreasing=T),]
head(temp, n=10)

我知道R非常好,因此我假设可以轻松地自动创建(并命名)前10位的虚拟变量并将其余变量折叠为最终的虚拟变量,称为其他。

I know R is great, so I am assuming there is an easy to auto-create (and name) the dummy variables from the top 10 and collapse the rest into a final dummy called 'other.'

在此先感谢您的帮助或见解。

Thanks in advance for any help or insight.

推荐答案

您很少需要伪变量-R会为您静默创建它们。

You rarely need dummy variables -- R silently creates them for you.

如果只想把所有不在前10名的类放在一起,则
可以简单地使用 ifelse %in%

If you just want to put all the classes that are not in the top 10 together, you can simply use ifelse and %in%.

x <- sample( LETTERS, 1e4, replace=TRUE, p=runif(26) )
top10 <- names( sort(table(x), decreasing=TRUE)[1:10] )
y <- ifelse( x %in% top10, as.character(x), "Rest" )
table(y)

如果绝对需要伪变量,可以使用 model.matrix 创建它们。

If you absolutely need dummy variables, you can create them with model.matrix.

model.matrix(~y) 

这篇关于R中的自动虚拟变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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