繁体   English   中英

在 R- 对于所有为 TRUE 的值,是同一行,前一列也为 TRUE?

[英]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

因为我问的是上一栏,所以需要在开头加一个null栏

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

对于每一行,如果是 TRUE,它是 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM