![](/img/trans.png)
[英]R : adding the values in a [row,column] only if value is true in (same) row, (different) column
[英]in R- for all values that are TRUE, is the same row, previous column also TRUE?
在 R 中。 我正在尝试生成一个充满逻辑的数据框,告诉我所有为 TRUE 的值,前一列中的同一行是否也为 TRUE。 列代表时间点,我想知道任何为真的行,它是该行的第一个实例为真吗? 注意 - 我只需要它查看一个时间点(列)。 如果在三列之前是真的,但不是在最后一列,它仍然被认为是一个新实例。
T1<- c(TRUE, TRUE, FALSE)
T2<- c(FALSE, TRUE, FALSE)
T3<- c(TRUE, FALSE, TRUE)
df<- data.frame(cbind(T1,T2,T3))
df
好像:
T1 T2 T3
1 TRUE FALSE TRUE
2 TRUE TRUE FALSE
3 FALSE FALSE TRUE
df_w_null<-cbind("null_col"= logical(nrow(df)), df)
df_w_null
null_col T1 T2 T3
1 FALSE TRUE FALSE TRUE
2 FALSE TRUE TRUE FALSE
3 FALSE FALSE FALSE TRUE
for (i in 2:ncol(df_w_null)){
status[i]<- as.data.frame(apply((!df_w_null[,i, drop=FALSE] == df_w_null[,i-1, drop=FALSE]), 1, isTRUE))
status<- data.frame(status)
return(status)
}
好像:
status[,2:ncol(df_w_null)]
1 TRUE TRUE TRUE
2 TRUE FALSE TRUE
3 FALSE FALSE TRUE
#expected result:
1 TRUE FALSE TRUE
2 TRUE FALSE FALSE
3 FALSE FALSE TRUE
这里有很多小步骤。 首先, data.frame
被拆分成列对,然后检查这些列对以查看它们是否满足FALSE
然后TRUE
的要求,然后将生成的逻辑向量重新组合成最终的data.frame
。
as.data.frame(do.call(cbind, lapply(setNames(lapply(2:ncol(df_w_null), function(x) data.frame(df_w_null[x-1], df_w_null[x])), names(df_w_null)[-1]),
function(x) ifelse(x[,1] == F & x[,2] == T, T, F))))
T1 T2 T3
1 TRUE FALSE TRUE
2 TRUE FALSE FALSE
3 FALSE FALSE TRUE
这是第一列中所有值的数据框FALSE
df1 <- cbind(FALSE, df)
只要列i
不为 TRUE(我们对最后一列不感兴趣,因此,df1[, -ncol(df1)]
)并且i + 1
列为 TRUE(我们不感兴趣),您就想要一个 TRUE 值在第一列,所以df1[, -1]
)。 我们有
> (!df1[, -ncol(df1)]) & (df1[, -1])
T1 T2 T3
[1,] TRUE FALSE TRUE
[2,] TRUE FALSE FALSE
[3,] FALSE FALSE TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.