Search code examples
phprstat

as.numeric is not working


I am developing code with R and trying to integrate it with PHP. In this code after the as.numeric, values will be output as NA on logs.txt and this N = '"15","20","30","40","50"'; (coming from PHP)

# my_rscript.R

args <- commandArgs(TRUE)
N <- args[1]

N=c(N)

cat(N,file="c:/rlogs.txt",append=TRUE)

N=as.numeric(as.character(N))

cat(N,file="c:/rlogs.txt",append=TRUE)

png(filename="temp.png", width=500, height=500)
hist(N, col="lightblue")
dev.off()

I really appreciate your help on this.


Solution

  • Without more detail, you first need to convert the input from a single string to a vector.

    That is, you need to strsplit, and in this case gsub to get rid of the extra quotation marks:

    N <- '"15","20","30","40","50"'
    
    as.numeric(N)
    # [1] NA
    # Warning message:
    # NAs introduced by coercion 
    
    N <- strsplit(N, ',')[[1]]
    N
    # [1] "\"15\"" "\"20\"" "\"30\"" "\"40\"" "\"50\""
    
    N <- gsub('"', '', N)
    N
    # [1] "15" "20" "30" "40" "50"
    
    N <- as.numeric(N)
    N
    # [1] 15 20 30 40 50