【问题标题】:Count factors of a variable depending of an other variable in a dataframe [duplicate]根据数据框中的其他变量计算变量的因子[重复]
【发布时间】:2015-07-09 13:38:03
【问题描述】:

我有一个 R 问题。我想根据数据框中的其他变量计算变量的因子。

我举个例子:

我有

    ID   com
    125 nul
    125 nul
    125 dec
    125 asc
    125 0
    130 nul
    130 dec

我想要什么

    ID|nul|dec|asc|0
    125|2|1|1|1
    130|1|1|0|0

注意:变量com 是一个因子,ID 是整数。

我尝试了我知道的简单方法:table(df$ID, df$com),但没有奏效。

【问题讨论】:

  • 根据给出的示例,您帖子中的代码适用于我

标签: r dataframe factors


【解决方案1】:

你可以试试dcast

library(reshape2)
dcast(df,ID~com, value.var='com', length)
#   ID nul dec asc 0
#1 125   2   1   1 1
#2 130   1   1   0 0

或者直接使用table

 table(df)
 #    nul dec asc 0
 #125   2   1   1 1
 #130   1   1   0 0

数据

df <- structure(list(ID = c(125L, 125L, 125L, 125L, 125L, 130L, 130L
 ), com = structure(c(1L, 1L, 2L, 3L, 4L, 1L, 2L), .Label = c("nul", 
"dec", "asc", "0"), class = "factor")), .Names = c("ID", "com"
), row.names = c(NA, -7L), class = "data.frame")

【讨论】:

  • 谢谢你,我用过 dcast 并且有效!!
  • @Marie 感谢您的反馈。我不明白为什么 table 命令对你不起作用。在我发布解决方案后看到了您的代码。
  • table 命令不起作用,因为它给了我很好的结果,但以一种我不想要的方式。我有 ID 变量、com 变量和频率。我想要的是每个因素都变成一个变量。
  • @Marie 可能是您在子集后的com 列中有未使用的级别。即table(droplevels(df)) 会起作用。 (由于格式不好,从 cmets 很难理解)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-11
  • 2021-04-02
  • 2020-06-13
  • 2019-01-29
  • 1970-01-01
相关资源
最近更新 更多