[R] Using if and else in a data frame

pannigh pannigh at gwdg.de
Thu Apr 26 17:21:45 CEST 2012


Dear list,
I get the ifelse function to work on a data frame but don't know how to do
something similar (only more conditions) with the combination of if and else
like in the example:

 A <- c("a","a","b","b","c","c")
 B <- c(rep(2,6))
 dat <- data.frame(A,B)
 dat$C <- if(AB$A=="a") {AB$B^2} else
          if(AB$A=="b") {AB$B+5} else
          if(AB$A=="c") {AB$B}

So I have a data frame (e.g. "dat") and want to create an new column for
that data frame applying certain conditions depending on the values of the
other columns of the data frame.

In this case I would like R to create a column with the following variables:
4,4,7,7,2,2. So if column A has the value "a" then do value of column B^2,
but if the value is "b" then do B-value + 5, and finally if the value in
column A is "c", then just copy the value of column B.

Hope someone can help... and thanx a lot!

--
View this message in context: http://r.789695.n4.nabble.com/Using-if-and-else-in-a-data-frame-tp4590153p4590153.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list