Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 为数据帧中的每列计算特定值跟随另一个特定值的次数_R_Count_Sequence - Fatal编程技术网

R 为数据帧中的每列计算特定值跟随另一个特定值的次数

R 为数据帧中的每列计算特定值跟随另一个特定值的次数,r,count,sequence,R,Count,Sequence,我想创建一个表或一个新的数据框,为原始数据框中的每一行显示一个特定值在另一个特定值之前的次数。例如,如果我有以下数据帧: 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")) 下面是一个使用stringr library(stringr) count_pair

我想创建一个表或一个新的数据框,为原始数据框中的每一行显示一个特定值在另一个特定值之前的次数。例如,如果我有以下数据帧:

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"))

下面是一个使用
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
库(stringr)

count\u对应该是
str\u count(s,pattern=p)
在函数true的最后一行中,我在后面添加了pattern参数,并忘记了该部分。谢谢你!这非常有效,但是有没有办法将输出作为数据帧或表?
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