将一列从分类转换为二进制,其余的保留 [英] Transform one column from categoric to binary, keep the rest

查看:73
本文介绍了将一列从分类转换为二进制,其余的保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个中等大小的数据框,为此,我想将具有类别的一列转换为二进制列,每个类别一列.

I have a medium large dataframe, for which I want to transform one column with categories to binary columns, one for each category.

同时,我想将其余的列保留在数据框中.

At the same time, I want to keep the rest of the columns in the dataframe.

最简单的方法是什么?

这是我想做的事的一个例子:

Here is an example of what I want to do:

d<-data.frame(ID=c("a","b","c","d"), Gender=c("male", "male", "female","female"), Age =c(23,45,18,11))

 ID Gender Age
1  a   male  23
2  b   male  45
3  c female  18
4  d female  11

此后应显示为d2,以便"ID"和年龄"列仍然存在且未被更改:

should look as d2 afterwards, so that the ID and Age columns are still there and untouched:

d2<-data.frame(ID=c("a","b","c","d"), Gender.male=c(1, 1, 0, 0), Gender.female=c(0,0,1,1), Age =c(23,45,18,11))

  ID Gender.male Gender.female Age
1  a           1             0  23
2  b           1             0  45
3  c           0             1  18
4  d           0             1  11

推荐答案

我们可以使用 spread

library(tidyvesre)
d %>% 
  mutate(n = 1) %>% 
  spread(Gender, n, fill = 0)

这篇关于将一列从分类转换为二进制,其余的保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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