我正在尝试创建一个" filter-by"矩阵,我可以用来隔离我的数据帧中的数据行,这样每行只包含对应于相同数字的最长连续序列的值,而其余的则保持为零。在搜索之后,我认为rle是使用的功能,但这并没有给我我想要的东西。这是我的代码和结果的示例。非常感谢建议和解决方案。谢谢!
示例数据:
a<- c(1,0,1,1,1,1,0,0)
b<- c(0,0,0,1,1,1,0,1)
c<- c(0,0,1,1,0,0,0,1)
d<- c(1,0,0,1,1,1,1,0)
e<- c(1,0,0,1,0,0,1,1)
f<- c(0,0,0,1,1,1,0,1)
g<- c(0,0,1,1,0,0,0,1)
test.data <- data.frame(cbind(a,b,c,d,e,f,g))
# > test.data
# a b c d e f g
# 1 1 0 0 1 1 0 0
# 2 0 0 0 0 0 0 0
# 3 1 0 1 0 0 0 1
# 4 1 1 1 1 1 1 1
# 5 1 1 0 1 0 1 0
# 6 1 1 0 1 0 1 0
# 7 0 0 0 1 1 0 0
# 8 0 1 1 0 1 1 1
用于解决方案的示例代码:
result <- data.frame(lapply(test.data, function(x) {
r <- rle(x)
r$values[r$lengths!=max(r$lengths)]==1
r2=inverse.rle(r)
r2
}))
结果我得到(看起来像进入的确切副本?):
# > result
# a b c d e f g
# 1 1 0 0 1 1 0 0
# 2 0 0 0 0 0 0 0
# 3 1 0 1 0 0 0 1
# 4 1 1 1 1 1 1 1
# 5 1 1 0 1 0 1 0
# 6 1 1 0 1 0 1 0
# 7 0 0 0 1 1 0 0
# 8 0 1 1 0 1 1 1
这是我想要获得的结果(如果更容易,可以使用T / F代替1和0):
# > result
# a b c d e f g
# 1 0 0 0 1 1 0 0
# 2 0 0 0 0 0 0 0
# 3 0 0 0 0 0 0 0
# 4 1 1 1 1 1 1 1
# 5 1 1 0 0 0 0 0
# 6 1 1 0 0 0 0 0
# 7 0 0 0 1 1 0 0
# 8 0 0 0 0 1 1 1
请建议!
答案 0 :(得分:0)
我认为你就是在追求......
test.data[] <- t(apply(test.data,1,function(x) {y<-rle(x)
y$values[y$lengths==1] <- 0
y$values[y$lengths!=max(y$lengths[y$values==1])] <- 0
return(inverse.rle(y))}))
test.data
a b c d e f g
1 0 0 0 1 1 0 0
2 0 0 0 0 0 0 0
3 0 0 0 0 0 0 0
4 1 1 1 1 1 1 1
5 1 1 0 0 0 0 0
6 1 1 0 0 0 0 0
7 0 0 0 1 1 0 0
8 0 0 0 0 1 1 1
答案 1 :(得分:0)
library(magrittr)
val <- 1
test.data %>%
apply(1, function(x){
rle(x) %$% {
if(all(values != val)) rep(0, length(x))
else {
m <- max(lengths[values == val])
# Get only longest sequences
values <- (lengths == m & values == val)*values*(m > 1)
# Get only one of them
values[seq_along(values) != which(values == val)[1]] <- 0
rep(values, lengths)
}
}}) %>% t
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] 0 0 0 1 1 0 0
# [2,] 0 0 0 0 0 0 0
# [3,] 0 0 0 0 0 0 0
# [4,] 1 1 1 1 1 1 1
# [5,] 1 1 0 0 0 0 0
# [6,] 1 1 0 0 0 0 0
# [7,] 0 0 0 1 1 0 0
# [8,] 0 0 0 0 1 1 1