基于多个条件的 Ifelse 函数
我正在尝试根据其他三个列(也是 TRUE/FALSE)的值创建一个新列(TRUE/FALSE)。 这是一个小样本。
DF
ID 1 2 3
1 TRUE NA NA
2 FALSE TRUE NA
3 TRUE TRUE NA
4 TRUE FALSE NA
5 TRUE FALSE TRUE
6 FALSE FALSE TRUE
7 TRUE FALSE FALSE
8 FALSE NA NA
9 NA NA NA
并非所有三列都具有相同的行数。 (因此有很多 NA 值)。这些数据是经过检查的文件,在第 2 列中,其中一些文件被重新检查,在第 3 列中,更小的部分再次被重新检查。
因此,第 2 列覆盖第 1 列,第 3 列覆盖第 1 列和第 2 列。
我希望以下输出
ID 1 2 3 4
1 TRUE NA NA TRUE
2 FALSE TRUE NA TRUE
3 TRUE TRUE NA TRUE
4 TRUE FALSE NA FALSE
5 TRUE FALSE TRUE TRUE
6 FALSE FALSE TRUE TRUE
7 TRUE FALSE FALSE FALSE
8 FALSE NA NA FALSE
9 NA NA NA FALSE
类是字符,所以我尝试使用函数 ifelse 和 grepl
DF$4 = ifelse(
grepl("TRUE", DF$1) |
grepl("TRUE", DF$2 |
grepl("TRUE", DF$3), "TRUE","FALSE" ))
但这只允许我为选项 TRUE 给出某些条件。我不知道如何实现如果第 2 列显示 FALSE 且第 1 列显示 TRUE 以获得输出 FALSE。
我尝试在 stackoverflow 中搜索类似的问题/答案(可能有),但我找不到它,因此我想在这里询问。 先感谢您。
I am trying to create a new column (TRUE/FALSE) based on the values of three other columns (also TRUE/FALSE).
This is a small sample.
DF
ID 1 2 3
1 TRUE NA NA
2 FALSE TRUE NA
3 TRUE TRUE NA
4 TRUE FALSE NA
5 TRUE FALSE TRUE
6 FALSE FALSE TRUE
7 TRUE FALSE FALSE
8 FALSE NA NA
9 NA NA NA
Not all three columns have the same amount of rows. (therefor a lot of NA values). The data were files that were checked and in column 2 some of them were re-checked and in column 3 an even smaller portion was again re-checked.
So Column 2 overrides column 1, and column 3 overrides column 1 and 2.
I would like the following output
ID 1 2 3 4
1 TRUE NA NA TRUE
2 FALSE TRUE NA TRUE
3 TRUE TRUE NA TRUE
4 TRUE FALSE NA FALSE
5 TRUE FALSE TRUE TRUE
6 FALSE FALSE TRUE TRUE
7 TRUE FALSE FALSE FALSE
8 FALSE NA NA FALSE
9 NA NA NA FALSE
Classes are character so ive tried it with the function ifelse and grepl
DF$4 = ifelse(
grepl("TRUE", DF$1) |
grepl("TRUE", DF$2 |
grepl("TRUE", DF$3), "TRUE","FALSE" ))
But this only allows me to give certain conditions for the option TRUE. I dont know how to implement if column 2 shows FALSE en column 1 shows TRUE to get the output FALSE.
I've tried to search stackoverflow for a similar question/answer, (there probably is) but i couldnt find it therefor i would like to ask it here.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以为每行取最后一个非 NA 值:
注意:自 R 4.1 起,
\
可以替换 lambda 类函数中的function
。You can take the last non-NA values for each rows:
Note:
\
can replacefunction
in lambda-like functions since R 4.1.