【问题标题】:Count number of times a particular value follows another particular value for each column in a data frame计算数据框中每一列的特定值跟随另一个特定值的次数
【发布时间】:2019-05-30 20:43:50
【问题描述】:

我想创建一个表格或一个新数据框,用于显示原始数据框中的每一行某个特定值先于另一个特定值的次数。例如,如果我有以下数据框:

x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "b", "a", "b", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))

我想知道,对于每种颜色(红色、蓝色和绿色),序列“b”、“a”出现了多少次(即序列中 b 在 a 之前出现了多少次)。

正确答案如下所示:

     Color ba
1   Red  1
2  Blue  3
3 Green  2

【问题讨论】:

    标签: r count sequence


    【解决方案1】:

    这是使用stringr的一种解决方案

    library(stringr)
    
    count_pair <- function(x, pattern) {
       p <- paste(pattern, collapse = "")
       s <- paste(x, collapse = "")
       str_count(s, pattern = p)
    }
    
    z <- apply(x, 2, count_pair, pattern = c("b", "a"))
    # Red  Blue Green 
    # 1     3     2 
    
    # if you want the output in form of a data.frame you could run:
    df <- as.data.frame(as.table(z))
    
    #    Var1 Freq
    # 1   Red    1
    # 2  Blue    3
    # 3 Green    2
    

    【讨论】:

    • 函数最后一行应该是str_count(s, pattern = p)
    • true,我后来添加了模式参数并忘记了那部分。谢谢
    • 谢谢!这很好用,但有没有办法将输出作为数据框或表格?
    猜你喜欢
    • 2020-09-12
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多