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 ?

M--
  • 25,431
  • 8
  • 61
  • 93
Chapo
  • 2,563
  • 3
  • 30
  • 60
  • `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 `<<-` whic is not recommend – 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[] <- lapply(a, as.numeric)`. If you want to take row-wise `sum` do `rowSums(a)` after that. – 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"]<- as.numeric(x["a"])` it converts `x["a"]` to numeric but since `x["b"]` is still a character it coerces `x["a"]` to character again. Same happens for `x["b"]`. – 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--
  • 25,431
  • 8
  • 61
  • 93