【问题标题】:R counting strings variables in each row of a dataframeR计算数据帧每一行中的字符串变量
【发布时间】:2015-05-02 20:45:18
【问题描述】:

我有一个看起来像这样的数据框,其中每一行代表一个样本,并且重复相同的字符串

> df
  V1 V2 V3 V4 V5
1  a  a  d  d  b
2  c  a  b  d  a
3  d  b  a  a  b
4  d  d  a  b  c
5  c  a  d  c  c

我希望能够创建一个新的数据帧,理想情况下,标题是前一个数据帧(a、b、c、d)中的字符串变量,每行的内容是每个数据帧的出现次数相应的变量来自 原始数据框。使用上面的示例,这看起来像

> df2
   a  b  c  d 
1  2  1  0  2  
2  2  1  1  1  
3  2  1  0  1
4  1  1  1  2  
5  1  0  3  1  

在我的实际数据集中,有数百个变量和数千个样本,所以如果我可以自动从原始数据帧中提取名称,并将它们按字母顺序排列到新数据帧的标题中,那将是理想的选择。

【问题讨论】:

    标签: r string dataframe


    【解决方案1】:

    你可以试试

    library(qdapTools)
    mtabulate(as.data.frame(t(df)))
    

    或者

    mtabulate(split(as.matrix(df), row(df)))
    

    或使用base R

    Un1 <- sort(unique(unlist(df)))
    t(apply(df ,1, function(x) table(factor(x, levels=Un1))))
    

    【讨论】:

      【解决方案2】:

      您可以stack 列然后使用table

      table(cbind(id = 1:nrow(mydf), 
                  stack(lapply(mydf, as.character)))[c("id", "values")])
      #    values
      # id  a b c d
      #   1 2 1 0 2
      #   2 2 1 1 1
      #   3 2 2 0 1
      #   4 1 1 1 2
      #   5 1 0 3 1
      

      【讨论】:

        猜你喜欢
        • 2015-02-12
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        • 1970-01-01
        • 2015-12-13
        • 1970-01-01
        • 2014-04-17
        相关资源
        最近更新 更多