【问题标题】:cbind for multiple table() functionscbind 用于多个 table() 函数
【发布时间】:2015-06-16 10:54:43
【问题描述】:

我正在尝试计算 data.frame 中多列的频率。

我在每一列上使用了table 函数,并通过cbind 将它们全部绑定,然后将使用聚合函数通过我的标识符计算平均值。 示例:

df1
V1       V2     V3
George   Mary   Mary  
George   Mary   Mary
George   Mary   George
Mary     Mary   George
Mary    George  George
Mary   
Frequency<- as.data.frame(cbind(table(df1$V1), table(df1$V2), table(df1$V3)))
row.names V1
George    3
Mary      3
          1
George    1
Mary      4
          1
George    3
Mary      2

我(视觉上)得到的结果是一个 2 列数据框,但是当我检查 Frequency 的维度时,我得到的结果暗示仅存在第二列。

当我尝试重命名列并运行聚合函数时,这给我带来了麻烦,重命名时出现错误:

colnames(Frequency) <- c("Name", "Frequency")
Error in names(Frequency) <- c("Name", "Frequency") : 
  'names' attribute [2] must be the same length as the vector [1]

最终目的是运行聚合命令并通过名称获取平均值:

Name.Mean<- aggregate(Frequency$Frequency, list(Frequency.Name), mean)

期望的输出:

Name   Mean
George Value
Mary   Value

【问题讨论】:

  • 您能否根据该示例显示示例数据和预期结果。如果df1 是您的数据集。尝试table(stack(df1))cbinding table 不同列的输出可能会导致警告消息,因为长度可能不同。
  • 请使用编辑按钮在您的帖子中更新它
  • 在运行您的代码时,我得到了一个完全不同的Frequency。此外,colnames(Frequency) &lt;- c("Name", "Frequency") 没有任何意义,因为您只有一列。如果你想添加一个新列,你应该做Frequency$Name &lt;- row.names(Frequency)。虽然这对我来说仍然没有意义,因为 data.frame 首先不能有重复的行名。最后,如果你能向我们展示你想要的输出效果会更好。
  • 我明白你在说什么,我只是尝试使用打印功能查看Frequency,并得到了你描述的错误。我之前是通过View(Frequency) 查看它的,这就是为什么我只有 1 列(使用View(Frequency) 你可以看到 2 列)让我感到困惑。我已经编辑了 OP 的结尾来解释我想要的输出。

标签: r cbind


【解决方案1】:

使用mtabulate(数据来自@user3169080 的帖子)

library(qdapTools)
d1 <- mtabulate(df1)
is.na(d1) <- d1==0 
colMeans(d1, na.rm=TRUE)
# Alice George   Mary 
#  4.0    3.0    2.5 

【讨论】:

    【解决方案2】:

    我希望这就是您想要的:

    > df1
      V1     V2     V3
    1 George George George
    2   Mary   Mary  Alice
    3 George George George
    4   Mary   Mary  Alice
    5   <NA> George George
    6   <NA>   Mary  Alice
    7   <NA>   <NA> George
    8   <NA>   <NA>  Alice
    > ll=unlist(lapply(df1,table))
    > nn=names(ll)
    > nn1=sapply(nn,function(x) substr(x,4,nchar(x)))
    > mm=data.frame(ll)
    > mm$names=nn1
    > tapply(mm$ll,mm$names,mean)
    > Mean=tapply(mm$ll,mm$names,mean)
    > data.frame(Mean)
           Mean
    Alice   4.0
    George  3.0
    Mary    2.5
    

    【讨论】:

    • 就是这样!谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2018-11-20
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多