2

I have the following vector:

set.seed(1); v1 = rnorm(100, 40, 10)

fun1 <- function(x){
x = x - 1
return(x)
}

fun2 <- function(x){
x = x * 10
return(x)
}

fun3 <- function(x){
x = x / 5
return(x)
}

I would like to set up a loop for the length of the vector but apply different functions for the elements [i] :

fun1 for v1[1:20]&v1[41:60]
fun2 for v1[21:40]
fun3 for v1[61:100]

And then return a vector.

Turns out I have no idea really how to do it elegantly.

4
  • 4
    Why do you need a for loop? Why not just result[1:20]<-fun1(v1[1:20]) etc? Commented Aug 8, 2018 at 13:39
  • @doviod I wanted to create a new vector, so thought iterating through existing one and creating a new one makes sense. I guess I should create an empty vector first then? Commented Aug 8, 2018 at 13:44
  • 2
    A friendly tip: you can simplify your function definition to fun1 <- function(x) x - 1. Assignment and return are not necessary, R functions return the last line be default. Commented Aug 8, 2018 at 13:54
  • @snoram great tip! the less typing the better! Commented Aug 8, 2018 at 13:58

2 Answers 2

4

Using mapply:

unlist(mapply(function(myFun, x) myFun(x),
              myFun = list(fun1, fun2, fun1, fun3),
              x = list(v1[1:20], v1[21:40], v1[41:60], v1[61:100])))

If you can update us with the logic for using certain function for certain subset, then we can make this more automated instead of typing up values for myFun and x.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks that's a very nice solution. In my real problem i have messed up numbers with three types, so they appear as strings (type 1: 12.0324.99, type 2: 12.34.6789, type 3: 12.045687). I would like to apply a different function and convert to numeric for each type and would identify the numbers by ones with one ".", and those with two "." but a different number of characters separating them (2 vs 4) and for type 3 leave them as they are and convert to numeric
@MIH So your real funs are functions to convert different formatted numbers to numeric? If you post example data that actually represents your data, then you might get better solutions, maybe using regex, instead of all this looping problem.
2

Here are two solutions without a loop:

v2 <- numeric(length(v1))
i1 <- c(1:20, 41:60)
i2 <- 21:40
i3 <- 61:100
v2[i1] <- fun1(v1[i1]); v2[i2] <- fun2(v1[i2]); v2[i3] <- fun3(v1[i3]);
v2b <- numeric()
v2b[c(i1,i2,i3)] <- c(fun1(v1[i1]), fun2(v1[i2]), fun3(v1[i3]))
identical(v2, v2b)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.