if else statements in data frame

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

if else statements in data frame

ozgrerg
Dear R experts, I have again a problem. Let I have a data frame like below:

x y
----------
A A
A B
B B
A B

where x and y are the column names. I want to create a new column z where it is elements
will be like that, if at each row has there at least one 'B', then z will have value of B, if not then Z will
have missing value(NA) for the corresponding row. So my result data frame should be like below:

x y Z
------------------
A A NA
A B B
B B B
A B B

How can I do this with if else statements in R. Thanks a lot.  
Reply | Threaded
Open this post in threaded view
|

Re: if else statements in data frame

helin_susam
Hi ozgrerg,

I am not a "good" R user, but according to me you can do this;

data <- data.frame(x=c("A","A","B","A"), y=c("A","B","B","B"))
for (i in 1:nrow(data)){
if(data$x[i]=="B"||data$y[i]=="B") z[i]=c("B")
else
z[i]=c("NA")
}

cbind(data,z)
Reply | Threaded
Open this post in threaded view
|

Re: if else statements in data frame

ozgrerg
Thanks for the answers. They were very helpful. I did it like below.

data$z <- ifelse(data$x == "A" & data$y == "A", "NA", "B").

That is enough for today. I guess I learned a enough today. Thanks to everbody who tried to help.


Reply | Threaded
Open this post in threaded view
|

Re: if else statements in data frame

Brad Schneid
This post has NOT been accepted by the mailing list yet.
this might be a little more safe, otherwise you could have an x or y as a NA and get z=B

data$z <- ifelse(data$x == "B" | data$y == "B", "B", "NA")
Reply | Threaded
Open this post in threaded view
|

Re: if else statements in data frame

ozgrerg
Thanks  alot B77S. That was a critical post.