【问题标题】:How to quickly create dummy variables from list in R如何从R中的列表快速创建虚拟变量
【发布时间】:2016-12-12 23:40:39
【问题描述】:

所以我是使用 R 的新手,但我在完成一项相当简单的任务时遇到了麻烦。我有一个名为“数据”的df,如下所示......

           Group       Score.Diff
Row 1   Kyle, Steve      15
Row 2   Matthew, Tony    12 
...     ...              ...            
Row n   Anthony, Zack    -10

我还有一个名为“Player.Names”的向量,其中包含在 Data$Group 中某个时间点出现的所有唯一名称,就像这样...

        Names
Row 1   Anthony
Row 2   Kyle
...     ...
Row n   Zack

我正在努力完成的是在“数据”中创建代表每个唯一名称的新列,如果名称在 Data$Group 中,则包含值 1,如果不在,则包含值 0。所需的输出如下所示...

           Group       Score.Diff  Anthony  Kyle  Steve ...  Zack
Row 1   Kyle, Steve      15           0      1     1    ...   0
Row 2   Matthew, Tony    12           0      0     0    ...   0
...     ...              ...         ...    ...   ...   ...  ...
Row n   Anthony, Zack    -10          1      0     0    ...   1

【问题讨论】:

  • 你真的应该避免每行有多个值的列。这是您在列内使用逗号分隔值的第二个问题。您可能想阅读tidy data。如果您有整洁的数据,那么在 R 中处理数据会变得更加容易。

标签: r dummy-variable


【解决方案1】:

我们可以使用 grepl 和模式作为 'df2' 中的 'Names' 列(使用 sapply 循环)来返回 'Group' 列的逻辑向量,使用 as.integer 和 @987654324 强制转换为二进制@ 与第一个数据集 ('df1')。

cbind(df1, sapply(df2$Names, function(x) as.integer(grepl(x, df1$Group))))
#               Group Score.Diff Anthony Kyle Zack
#Row 1   Kyle, Steve         15       0    1    0
#Row 2 Matthew, Tony         12       0    0    0
#Row n Anthony, Zack        -10       1    0    1

###数据

df1 <- structure(list(Group = c("Kyle, Steve", "Matthew, Tony",
 "Anthony, Zack"
), Score.Diff = c(15L, 12L, -10L)), .Names = c("Group", "Score.Diff"
), class = "data.frame", row.names = c("Row 1", "Row 2", "Row n"))

df2 <- structure(list(Names = c("Anthony", "Kyle", "Zack")), 
   .Names = "Names", class = "data.frame", row.names = c("Row 1", "Row 2",  "Row n"))

【讨论】:

  • 非常感谢!
  • @DeJay 没问题。很高兴为您提供帮助。
猜你喜欢
  • 2015-10-22
  • 2015-08-11
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 2020-04-03
  • 1970-01-01
相关资源
最近更新 更多