[R] Using if and else in a data frame
Rui Barradas
ruipbarradas at sapo.pt
Thu Apr 26 18:14:09 CEST 2012
Hello,
Your example code has a bug, there's no fata.frame called 'AB'. It's
corrected below.
pannigh wrote
>
> 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!
>
Now, let's run it.
A <- c("a","a","b","b","c","c")
B <- c(rep(2,6))
dat <- data.frame(A,B)
dat$C <- if(dat$A=="a"){dat$B^2} else
if(dat$A=="b") {dat$B+5} else
if(dat$A=="c") {dat$B}
Warning message:
In if (dat$A == "a") { :
the condition has length > 1 and only the first element will be used
'ifelse' is vectorized, 'if / else' is not. The condition does have length >
1:
dat$A=="a"
[1] TRUE TRUE FALSE FALSE FALSE FALSE
Length 6, only the first, TRUE, is used and dat$C <- dat$B^2.
The solution is to use 'ifelse'.
dat <- data.frame(A,B)
dat$C <- ifelse(dat$A == "a", dat$B^2,
ifelse(dat$A == "b", dat$B + 5, dat$B))
Hope this helps.
Rui Barradas
--
View this message in context: http://r.789695.n4.nabble.com/Using-if-and-else-in-a-data-frame-tp4590153p4590279.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list