4

How do I create the following function in R?

f(1)=1 f(2)=2 f(3)=3 f(4)=1 f(5)=2 f(6)=3 f(7)=1 f(8)=2 f(9)=3 

and so on...

I have tried to use different loops, but have not been able to do the job.

2 Answers 2

4

Try this

Myfunc <- function(x) (x + 2L) %% 3L + 1L 

Testing

Myfunc(1) ## [1] 1 Myfunc(2) ## [1] 2 Myfunc(3) ## [1] 3 Myfunc(1:9) ## [1] 1 2 3 1 2 3 1 2 3 
Sign up to request clarification or add additional context in comments.

Comments

1

I don't know R but it can be done with Mod3 easily:

function modThree(x) { var mod = x%3; if(mod == 0) return 3; return mod; } 

2 Comments

For someone who doesn't know R, you're pretty close to R syntax. Make your first like modThree = function() {, get rid of var (don't have to declare things) and wrap your returns in parens return(3) and return(mod), and you've got a valid R function.
I've actually also used Mod3 in my answer... Either-way, you can modify this to modThree <- function (x) { mod = x%%3 ;ifelse(mod == 0, 3 , mod) } and then it''ll work

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.