1

Here, my main question is that my new variable would kept being named "x" instead of my own choice "newvar_test". I want a new variable that I name it myself in the () by using the old variable. This is then a new column named "newvar_test" in mydata. I understood I can use return but either didn't really work out.

 fun1<- function(x, y) {
            mutate(mydata, x = 
            ifelse(y == 10, 0,
            ifelse(y == 1, 0.5/7,
            ifelse(y == 2, 1/7, 
            ifelse(y == 3, 3/7,
            ifelse(y == 4, 5.5/7,
            ifelse(y == 5, 1,
            ifelse(y == 6, 2.5,
            ifelse(y==  7, 4.5,
             6)))))))))
                      }
mydata <- fun1(newvar_test, oldvar)
divibisan
  • 11,659
  • 11
  • 40
  • 58
mchsu
  • 31
  • 1
  • 5

1 Answers1

0

Is this what you mean?

y <- 1:11
get_val <- function(val) {
  val <- as.character(val)
  switch (val,
          "11" = 0,
          "1" = .5/7,
          "2" = 1/7,
          "3"= 3/7,
          "4" = 5.5/7,
          "5" = 1,
          "6" = 2.5,
          "7" = 4.5,
          6
  )    
}                                                    

x <- sapply(y, get_val)

x
> [1] 0.07142857 0.14285714 0.42857143 0.78571429 1.00000000 2.50000000 4.50000000 6.00000000
> [9] 6.00000000 0.00000000 6.00000000

The function uses the switch statement to reassign the values you put into it. Then (instead of looping) you apply the function to the whole vector y with sapply.

MartijnVanAttekum
  • 1,405
  • 12
  • 20
  • Hi Martijn, I edited my question. I am hoping to get a new variable that I can name it myself in the dataset at this point. I am not sure if I am thinking too much like I am writing a macro in SAS. Here is R code. Thank you! – mchsu Sep 12 '18 at 16:31