If and & is a statement in R

I have a data.frame with 4 columns:

> bb
               V1      V2      V3       V4
1         ARFGEF2 ARFGEF2 ARFGEF2     <NA>
2           SFRS5    <NA>   SRSF5     <NA>
3 ENSG00000215104    <NA>    <NA> CHMP1B2P
4            EDF1    EDF1    EDF1     <NA>
5    LOC100133678    <NA>    <NA>     <NA>
6            CD3G    CD3G       -     <NA>
7           GNAI2   GNAI2   GNAI2     <NA>

I want to create a new column according to the values ​​in columns 2, 3 and 4. What I tried to do: If bb[,2]is NAAND bb[,3]has a value, then it bb[,5]will be a value bb[,3], if bb[,2]is NAAND bb[,3]is NAand df[,4]has a value, then it bb[,5]will be a value bb[,4], otherwise it bb[,5]will df[,1]. Here is the expected result:

> bb
                V1      V2      V3       V4       V5
1          ARFGEF2 ARFGEF2 ARFGEF2     <NA>  ARFGEF2
2            SFRS5    <NA>   SRSF5     <NA>    SRSF5
3  ENSG00000215104    <NA>    <NA> CHMP1B2P CHMP1B2P
4             EDF1    EDF1    EDF1     <NA>     EDF1
5     LOC100133678    <NA>    <NA>     <NA>     <NA>
6             CD3G    CD3G       -     <NA>        -
7            GNAI2   GNAI2   GNAI2     <NA>    GNAI2

I tried this code but it does not work:

> for (i in 1:nrow(bb)){
      if (is.na(bb[i,2] & !(is.na(bb[i,3])))) {bb[i,5] <- as.character(bb[i,3])}
    else if (is.na(bb[i,2]) & !(is.na(bb[i,4]))) {bb[i,5] <- as.character(bb[i,4])}
    else { bb[i,5] <- bb[i,1]}
}
Warning messages:
 1: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 2: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 3: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 4: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 5: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 6: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors
 7: In Ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) :
  & not meaningful for factors

& if? data.frame, (V5), V1, V2 NA. V2 NA, , V3 TRUE, V5 V3 , -, V3 NA V4 , V5 V4, , V3 V4 NA, V5 V1.

+4
1

for && &. is.na. ifelse, -

bb[,5] <- ifelse(is.na(bb[,2]) & !is.na(bb[,3]), 
            bb[,3], 
            ifelse(is.na(bb[,2]) & !is.na(bb[,4]), bb[,4], bb[,1])
          )

()

+2

Source: https://habr.com/ru/post/1535284/


All Articles