通过将重复的行散布到R中的列中来创建“虚拟变量” [英] Create 'dummy variables' by spreading duplicate rows into columns in R

查看:84
本文介绍了通过将重复的行散布到R中的列中来创建“虚拟变量”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

预先感谢您的帮助。

使用价差有几个问题(从长到宽)在具有 unite 的重复行上,例如

There are several questions using spread (from long to wide) on duplicate rows with unite such as this.

我认为使我的问题与众不同的原因是需要输出虚拟变量。

I think what makes my question unique is the need to output dummy variables.

我希望输入如下:

df <- data.frame(id = c(1,1,2,3,4), fruit = c("apple","pear","apple","orange","apple"))

这样的输出:

output <- data.frame(id=c(1,2,3,4), apple = c(1,1,0,1), pear = c(1,0,0,0), orange = c(0,0,1,0))

任何帮助将不胜感激。谢谢。

Any help would be greatly appreciated. Thanks.

推荐答案

使用 tidyverse ,您可以添加新列,然后使用价差

Using tidyverse you can add new column and than use spread.

library(tidyverse)

df %>% mutate(i = 1) %>% spread(fruit, i, fill = 0)

# result
  id apple orange pear
1  1     1      0    1
2  2     1      0    0
3  3     0      1    0
4  4     1      0    0

这篇关于通过将重复的行散布到R中的列中来创建“虚拟变量”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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