taha ismet sevgili
taha ismet sevgili

Reputation: 3

I tried to write a similar function to as.numeric in r for my data, but there is a problem

I have a column of soccer game goal times. Entries are character strings, in the format of "43" or "90+2". In R, as.numeric() converts character array "43" to numeric 43, but converts "90+2" to NA. I want a function which turns values like the latter to 92.

I tried:

function(y) {
    x = vector(mode='numeric',length=length(y))  
    for(i in 1:length(y)) {
      for(j in 1:nchar(y[i])) {
        if(substring(y[i],j,j)=="+") {
          x[i]=as.numeric(substring(y[i],1,j-1))+as.numeric(substring(y[i],j+1,nchar(y[i])))
        }
        if((substring(y[i],j,j)!="+") & (j==nchar(y[i]))) {
          x[i]=as.numeric(y[i])  
        }
      }
    }
    return(x)
}   

But it doesn't work out in the values like "90+2". I couldn't spot my error. Please help me.

Upvotes: 0

Views: 188

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269441

There should be a break statement after the first statement assigning a value to x[i]. If we call the revised function Sum then we get:

y <- c("90+2", "33") # test input
Sum(y)
## [1] 92 33

Note that this would also work:

sapply(strsplit(y, "+", fixed = TRUE), function(x) sum(as.numeric(x)))
## [1] 92 33

as would this which returns a named numeric vector:

sapply(y, function(x) eval(parse(text = x)))
## 90+2   33 
##   92   33 

Upvotes: 3

Related Questions