我想创建一个表或一个新的数据框,为原始数据框(其中有许多列)中的每一列显示一个特定值的序列出现的次数。例如,如果我有以下数据帧:
x <- data.frame("Red" = c("a", "b", "a", "a", "c", "d"), "Blue" = c("b", "a", "a", "a", "a", "a"), "Green" = c("a", "a", "b", "a", "b", "a"))我想知道,对于每种颜色(红色、蓝色和绿色),值"a“发生了多少次(即,在它被另一个值中断之前,比如b或c)。
正确的答案如下所示:
Color a_sequences
1 Red 2
2 Blue 1
3 Green 3我已经在这个网站上找到了对单个向量使用rle函数的解决方案,但我不知道如何将其扩展到具有多列的整个数据帧,并获得具有序列计数的新表或数据帧,如上表所示。谢谢!
发布于 2019-05-31 09:37:07
f = function(v, ch) sum(rle(as.character(v))$values == ch)
sapply(x, f, 'a')
# Red Blue Green
# 2 1 3 发布于 2019-05-31 10:03:52
下面是一个使用tidyverse的选项,我们将值转换为‘gather’格式,按'color‘分组,以及’rleid‘的游程长度id (rleid),将'a’的‘filter’元素取值,然后按'color‘分组,得到不同的'grp’元素的数量
library(tidyverse)
library(data.table)
gather(x, color, value) %>%
group_by(color, grp = rleid(value)) %>%
filter(value == "a") %>%
group_by(color) %>%
summarise(n = n_distinct(grp))
# A tibble: 3 x 2
# color n
# <chr> <int>
#1 Blue 1
#2 Green 3
#3 Red 2或summarise_all的一个选项
x %>%
summarise_all(list(~ n_distinct(setdiff((. == 'a') * rleid(.), 0)))) %>%
as.list %>%
enframe %>%
unnest
# A tibble: 3 x 2
# name value
# <chr> <int>
#1 Red 2
#2 Blue 1
#3 Green 3发布于 2019-05-31 11:19:26
这是另一个想法。我们可以合并和折叠所有字符串,拆分不是a的字符串,并计算包含a的元素的数量。result2是最终的结果。
result <- sapply(x, function(x) {
x2 <- as.character(x)
y <- paste0(x2, collapse = "")
z <- strsplit(y, "[^a]")[[1]]
return(sum(grepl("a", z)))
})
result2 <- data.frame(Color = names(result), a_sequence = unname(result))
result2
# Color a_sequence
# 1 Red 2
# 2 Blue 1
# 3 Green 3https://stackoverflow.com/questions/56387584
复制相似问题