2
    a <- data.frame(a=c("1","2","3"),b=c("1","2","3"))
    apply(a,1,function(x) {
      x["a"]<- as.numeric(x["a"])
      x["b"]<- as.numeric(x["b"])
      return(x["a"]+x["b"])
    })

Why am I getting

Error in x["a"] + x["b"] : non-numeric argument to binary operator

?

Can I not modify values from within the apply loop ?

Chapo
  • 2,339
  • 3
  • 23
  • 51
  • `return(as.numeric(x["a"])+as.numeric(x["b"]))` you just need this. And no, if you want to change them you need to use `assign` or `< – M-- Jul 11 '19 at 06:13
  • Why are you individually changing the values? You can directly do `as.numeric(x)` in the `apply` function. What is the output that you are expecting? If you want to change the value to numeric use `a[] – Ronak Shah Jul 11 '19 at 06:16
  • it was just a simplified example. some of my columns are numeric some not and in my `apply` I need both. I'll have to do `as.numeric` each time then – Chapo Jul 11 '19 at 06:17
  • @M-M if you make it into an answer I'll validate it – Chapo Jul 11 '19 at 06:18
  • 1
    The reason why your attempt doesn't work is because `x` in your `apply` call is vector and vector can hold only one type of value. When you do `x["a"] – Ronak Shah Jul 11 '19 at 06:27

1 Answers1

2

You can do this:

apply(a,1,function(x) as.numeric(x["a"]) + as.numeric(x["b"]))
M--
  • 20,766
  • 7
  • 52
  • 87