-2

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.

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
parker
  • 39
  • 7
  • 4
    What do you mean by "isn't working"? And is `N` literally just the string `'"15","20","30","40","50"'`? If so then you need to split the string first... – shadowtalker Jun 13 '15 at 17:50
  • 3
    Or use `scan` i.e. `as.numeric(scan(text=N, sep=",", what=''))` – akrun Jun 13 '15 at 17:53

1 Answers1

2

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
shadowtalker
  • 12,529
  • 3
  • 53
  • 96