r - assigning columns using ifelse and within -


why function ifelse , within cannot work together? example illustrate problem, have following code. wanted create 2 columns (petal.dim1 , petal.dim2 petal.width , petal.length) switches whenever sepal.length greater 5.

data(iris) within(iris, ifelse(sepal.length>5,{                 petal.dim1 <-petal.width                 petal.dim2 <-petal.length             }, {                 petal.dim1<-petal.length                 petal.dim2<-petal.width})) 

i can not wrong code, can suggest use transform:

data(iris) dat <- transform(iris,      petal.dim1=ifelse(sepal.length>5, petal.width, petal.length),     petal.dim2=ifelse(sepal.length>5, petal.length, petal.width) ) str(dat) 

edit: more robust way (in opinion) store indizes , avoid within or transform:

idx <- iris[,"sepal.length"] > 5 dat <- iris dat[idx, "dim1"] <- petal.width dat[idx, "dim2"] <- petal.length dat[!idx, "dim1"] <- petal.length dat[!idx, "dim2"] <- petal.width 

maybe faster, not sure that.


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

netbeans - Remove indent guide lines -

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -