替换dataframe中满足特殊条件的行值
我需要将0替换为1,但仅当值组满足以下条件时;“1 0 1”或“0 1”(如果在开头)或“1 0”(如果在结尾)。给定示例数据帧:替换dataframe中满足特殊条件的行值,r,R,我需要将0替换为1,但仅当值组满足以下条件时;“1 0 1”或“0 1”(如果在开头)或“1 0”(如果在结尾)。给定示例数据帧: df <- data.frame(a = c(1,0,1,0,1,1,1,0,1,1,1), b = c(1,1,1,0,1,1,1,0,1,1,1), c = c(1,0,1,1,1,0,1,0,1,1,1), d = c(1,1,1,0,1,1,1,1,1
df <- data.frame(a = c(1,0,1,0,1,1,1,0,1,1,1),
b = c(1,1,1,0,1,1,1,0,1,1,1),
c = c(1,0,1,1,1,0,1,0,1,1,1),
d = c(1,1,1,0,1,1,1,1,1,1,1),
e = c(1,0,1,0,1,1,1,1,1,1,1),
f = c(1,1,1,1,1,1,1,1,1,0,1))
df
df这里有一个使用rle()的解决方案
:
如果需要数据帧作为结果,可以执行以下操作:
df.result <- df
df.result[,] <- t(apply(df,1,foo))
包zoo
中的df.resultrollappy()
可能对每一行都有用。。。或者rle()
来自base
谢谢!多好的解决方案啊。
foo <- function(x) {
r <- rle(x)
r$values[r$values==0 & r$lengths==1] <- 1
inverse.rle(r)
}
foo(c(0,1,0,0,1,0,1)) # testing the working horse:
# [1] 1 1 0 0 1 1 1
t(apply(df, 1, foo))
# > t(apply(df,1,foo))
# [,1] [,2] [,3] [,4] [,5] [,6]
# [1,] 1 1 1 1 1 1
# [2,] 1 1 1 1 1 1
# [3,] 1 1 1 1 1 1
# [4,] 0 0 1 0 0 1
# [5,] 1 1 1 1 1 1
# [6,] 1 1 1 1 1 1
# [7,] 1 1 1 1 1 1
# [8,] 0 0 0 1 1 1
# [9,] 1 1 1 1 1 1
# [10,] 1 1 1 1 1 1
# [11,] 1 1 1 1 1 1
df.result <- df
df.result[,] <- t(apply(df,1,foo))