Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error only when running whole block of code

Tags:

r

syntax-error

I have code that came with a dataset that I downloaded. This code is supposed to convert factor variables to numeric. When I run each line individually, it works fine, but if I try to highlight a whole section, then I get the following error:

Error: unexpected input in ...

It gives me this error for every line of code, but again if I run each line individually, then it works fine. I've never run into this before. What's going on?? Thanks!

Here's the code that I'm trying to run:

library(prettyR)
lbls <- sort(levels(DF$myVar))
lbls <- (sub("^\\([0-9]+\\) +(.+$)", "\\1", lbls))
DF$myVar <- as.numeric(sub("^\\(0*([0-9]+)\\).+$", "\\1", DF$myVar))
DF$myVar <- add.value.labels(DF$myVar, lbls)

And here is the output with the errors:

> library(prettyR)
"rror: unexpected input in "library(prettyR)
> lbls <- sort(levels(DF$myVar))
"rror: unexpected input in "lbls <- sort(levels(DF$myVar))
> lbls <- (sub("^\\([0-9]+\\) +(.+$)", "\\1", lbls))
"rror: unexpected input in "lbls <- (sub("^\\([0-9]+\\) +(.+$)", "\\1", lbls))
> surv.df$myVar <- as.numeric(sub("^\\(0*([0-9]+)\\).+$", "\\1", DF$myVar))
"rror: unexpected input in "DF$myVar <- as.numeric(sub("^\\(0*([0-9]+)\\).+$", "\\1",DF$myVar))
> surv.df$BATTLEGROUND <- add.value.labels(DF$myVar, lbls)
Error in add.value.labels(surv.df$myVar, lbls) : 
object 'lbls' not found
like image 959
user3658457 Avatar asked Oct 19 '14 15:10

user3658457


1 Answers

I figured out the issue (actually someone told me what the problem was)

The code was downloaded as a .R file and must have been written using a text editor with non-standard "new line" coding. So I just copied the code to a text editor, did replace all to switch "\n" to "#####". Then I used replace all again to switch back to new-lines and copied it back into R studio.

And everything works!

like image 140
user3658457 Avatar answered Oct 13 '22 17:10

user3658457