[R] Function - simple question

chuck.01 CharlieTheBrown77 at gmail.com
Thu Apr 5 23:59:20 CEST 2012


This is one way:

f <- function(x, y){
 Z <- ifelse(x==y, 3, 4)
 return(Z)
}

DS[3] <- with(DS, f(X,Y))
colnames(DS)[3] <- "Z"

But you don't really need a function to do that.

DS[3] <-  with(DS, ifelse(X==Y, 3, 4))   # this works just fine

I'm glad you've decided to use R; eventually you will need to read some
intro R manuals.  

Cheers. 




flacerdams wrote
> 
> Dear all,
> 
> Suppose I have a dataset with two variables:
> 
> X = c(0, 1, 2)
> Y = c(1, 1, 1)
> DS = data.frame(X, Y)
> 
> Now, I want to create a new variable Z with 3 observations, but I want its
> values to be the result of a function. I want to create a function that
> compares X and Y, and if X = Y, then Z value = 3. If X value differs from
> Y value, Z value = 4. So, I'd have the following values for Z: 4, 3, 4.
> 
> How can I create a function like that? (Sorry, I know it's a dumb
> question, I began to use R two days ago)
> 
> Thank you very much,
> 
> Lacerda
> 


--
View this message in context: http://r.789695.n4.nabble.com/Function-simple-question-tp4536162p4536189.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list