if and & statement in R -
i have data.frame 4 columns that:
> 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 create new column according values on columns 2, 3, , 4. trying : if bb[,2]
na
and bb[,3]
has value bb[,5]
value of bb[,3]
, if bb[,2]
na
and bb[,3]
na
, df[,4]
has value bb[,5]
value of bb[,4]
, else bb[,5]
df[,1]
. here expected output:
> 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've trying code doesn't work:
> (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 factors 2: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors 3: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors 4: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors 5: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors 6: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors 7: in ops.factor(bb[i, 2], !(is.na(bb[i, 3]))) : & not meaningful factors
how use &
if
statement? example of longer data.frame create new column (v5
) taking values of v1
if v2
not na
. in case of v2
being na
, first want check whether v3
has value , if true
v5
v3
value, second, if v3
na
, v4
has value v5
value of v4
, if v3
, v4
na
v5
v1
.
many thanks
your for
loop should using &&
instead of &
. missing bracket @ first is.na
. try ifelse
function, along lines
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]) )
(untested)
Comments
Post a Comment