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