error: unexpected input - r

Observe following code:
Xij <- scan(n=45)
6398400 6273897 6038777 5810740 5673521 5688332 5669445 5682840 5679432
5723561 5555929 5345696 5321179 5199592 5165409 5130744 5132372
4717909 4925673 4999103 4960733 4840036 4824080 4821902
7115151 7114401 7039423 6967723 6967513 6901684
8203359 8286980 8222974 8323470 8067521
5930080 5862383 5994123 6017566
5558436 5754304 5613530
4595506 5074887
3443322
n <- length(Xij); TT <- trunc(sqrt(2*n))
i <- rep(1:TT,TT:1); j <- sequence(TT:1)
i <- as.factor(i); j <- as.factor(j)
If I now try to run following command:
Xij.1 <- xtabs(Xij˜i+j)
I get the error 'Error: unexpected input in "Xij.1 <- xtabs(Xij˜"
This exercise is however, analog to an example from the book 'Modern Actuarial Risk Theory using R'.
Does somebody know what is possibly wrong?

It works fine:
xtabs(Xij~i+j)
Notice that in R formula you have to use tilde character ~ rather then ˜ character. Those are two different characters.

Related

Print text with subscripts (programatically) to R console

I'm using R to balance some complex chemical equations and would like to print these equations including subscripts to the console as the code runs. I've seen some answers posted, most of which are related to plots or rely on pasting the subscript from another program into R scripts:
Subscripts in R when adding other text
How to literally print superscripts in R not used in labels or legends?
Using Subscripts and Superscripts in R console
Unicode subscript in R had some pointers that were helpful. I can get the appropriate code from this link but it doesn't allow me to programatically create the code for the character I want.
CODE
Here's a simple example equation for combustion of methane that works:
> sub2 <- '\u2082' # hard-coding unicode for '2' as a subscript
> sub4 <- '\u2084' # hard-coding unicode for '4' as a subscript
> cat(sprintf('CH%s + 2 O%s --> CO%s + 2 H%sO', sub4, sub2, sub2, sub2))
CH₄ + 2 O₂ --> CO₂ + 2 H₂O
Lengthy workaround (proof-of-concept):
desired_subscript <- 3.375
subs <- c('\u2080', '\u2081', '\u2082', '\u2083', '\u2084',
'\u2085', '\u2086', '\u2087', '\u2088', '\u2089')
charvec <- as.character(x = desired_subscript)
lapply(0:9, function(z){
charvec <<- gsub(pattern = z, replacement = subs[z+1], x = charvec)
return(NULL)
})
> cat(charvec)
₃.₃₇₅
Here's what doesn't work:
replacing the last digit of the unicode string to what I want:
> cat(sub(pattern = '2', replacement = '4', x = sub2))
₂
Trying to create a unicode string:
> paste('\208','4',sep = '')
[1] "\02084"
I have multiple equations to balance and the subscripts are not always whole numbers. Is there a way to programatically get unicode for the subscript that I want to include in my output to console?
Try this
create a function to return unicodes. Caution: No error checking
ss <- function(x) {intToUtf8(0x2080 + x)}
cat(sprintf('CH%s + 2 O%s --> CO%s + 2 H%sO', ss(4), ss(2), ss(2), ss(2)))

Calling CustomCSVIter function using mxnet pacakge in R

I'm trying to train a list of text datasets at the character level (for example, a cat => "a", " ", "c", "a", "t") so that I can classify them with great accuracy. I'm using mxnet package (CNN Network) in R and using crepe model. So to prepare for training, I need to do iterations for both training and test datasets. So the code is as follow:
train.iter <- CustomCSVIter$new(iter=NULL, data.csv=train.file.output,
batch.size=args$batch_size, alphabet=alphabet,
feature.len=feature.len)
test.iter <- CustomCSVIter$new(iter=NULL, data.csv=test.file.output,
batch.size=args$batch_size, alphabet=alphabet,
feature.len=feature.len)
data.csv where I have these datasets, batch.size is just an integer, feature.len is also just an integer, and alphabet is a vector of alphanumeric quotations (abcd...?!""). When I run the above code, I get a message saying I have a fatal error and Rstudio crashes and reloads. I don't know what I'm doing wrong. To run the above code, you need the following function:
CustomCSVIter <- setRefClass("CustomCSVIter",
fields=c("iter", "data.csv", "batch.size",
"alphabet","feature.len"),
contains = "Rcpp_MXArrayDataIter",
methods=list(
initialize=function(iter, data.csv, batch.size,
alphabet, feature.len){
csv_iter <- mx.io.CSVIter(data.csv=data.csv,
data.shape=feature.len+1, #=features + label
batch.size=batch.size)
.self$iter <- csv_iter
.self$data.csv <- data.csv
.self$batch.size <- batch.size
.self$alphabet <- alphabet
.self$feature.len <- feature.len
.self
},
value=function(){
val <- as.array(.self$iter$value()$data)
val.y <- val[1,]
val.x <- val[-1,]
val.x <- dict.decoder(data=val.x,
alphabet=.self$alphabet,
feature.len=.self$feature.len,
batch.size=.self$batch.size)
val.x <- mx.nd.array(val.x)
val.y <- mx.nd.array(val.y)
list(data=val.x, label=val.y)
},
iter.next=function(){
.self$iter$iter.next()
},
reset=function(){
.self$iter$reset()
},
num.pad=function(){
.self$iter$num.pad()
},
finalize=function(){
.self$iter$finalize()
}
)
)
Usually a problem like this arises when there is a mismatch between shapes of the input file and the data.shape parameter of the iterator.
You can easily check if this is the problem by running your code outside from RStudio. Run R from terminal/command line and paste your code there. When an exception happens, it will terminate the R session, and you will be able to read the exception message. In my case it was:
Check failed: row.length == shape.Size() (2 vs. 1) The data size in CSV do not match size of shape: specified shape=(1,), the csv row-length=2
In your case it is probably something similar.
Btw, there is an implementation of a custom iterator for MNIST dataset, which you may find useful: https://github.com/apache/incubator-mxnet/issues/4105#issuecomment-266190690

Object 'sef' not found in R corr.test

I am attempting to run the corr.test equation in R, with code that my professor submitted and tested on his system. Unfortunately, when I run it I am getting an error that "object sef not found".
This is confounding both my professor and I, and having done a thorough search, we're not sure how to address this.
I really appreciate any help you can provide.
Edit: Here is the code I am using:
trendan1 <- read.table("trendan1.for.R.dat", header=TRUE, na.strings=".")
head(trendan1)
tail(trendan1)
attributes(trendan1)
is.matrix(trendan1)
id <- trendan1$id
famenv1 <- trendan1$famenv1
famenv2 <- trendan1$famenv2
famenv3 <- trendan1$famenv3
conf1 <- trendan1$conf1
conf2 <- trendan1$conf2
conf3 <- trendan1$conf3
trendan1dataset1 <- cbind(id,famenv1,famenv2,famenv3,conf1,conf2,conf3)
attributes(trendan1dataset1)
is.matrix(trendan1dataset1)
is.data.frame(trendan1dataset1)
require("psych")
describe(trendan1dataset1[,2:7])
print(describe(trendan1dataset1[,2:7]), digits=6)
famave <- (1*famenv1 + 1*famenv2 + 1*famenv3)/3
famlin <- -1*famenv1 + 0*famenv2 + 1*famenv3
famquad <- 1*famenv1 - 2*famenv2 + 1*famenv3;
trendandataset2 <- cbind(famenv1,famenv2,famenv3,famave,famlin,famquad)
print(describe(trendandataset2), digits=6)
hist(famenv1)
boxplot(famenv1)
abline(h=mean(famenv1))
qqnorm(famenv1,ylab="famenv1")
qqline(famenv1)
shapiro.test(famenv1)
hist(famenv2)
boxplot(famenv2)
abline(h=mean(famenv2)) # add mean to the boxplot
qqnorm(famenv1,ylab="famenv2")
qqline(famenv2)
shapiro.test(famenv2)
corvars1 <- cbind(famenv1,famenv2,famenv3)
cor(corvars1,use = "everything", method = "pearson")
cov(corvars1,use = "everything")
sscp1 <- t(corvars1)%*%(corvars1) #Matrix multiplcation
sscp1
rc1 <- corr.test(corvars1,
use="pairwise",method="pearson",adjust="holm",alpha=.05, ci=FALSE)
attributes(rc1)
print(rc1$p, digits=6)
This is a bug that sometimes happens when you do not evaluate confidence interval. It should be fixed if u change the option to ci=TRUE, or simply delete this option as the default is ci=TRUE.

Error message with objects in 'lsoda' in R

Very new user here. I am trying to use lsoda to solve differential equations stratified into two layers (as denoted by the for(s in 1:2) loop).
When running this full code, I keep getting the error message
object 'N' not found
no matter where or how I try to define N.
Can anyone help spot the error or advise on what I'm doing wrong? Thanks in advance.
R code:
library(deSolve)
Dyn <- function(t, var,par) {
with(as.list(c(par, var)), {
for(s in 1:2){
#Derivatives
dX[s] <- mu*N[s] - sigma*X[s] - (c[s]*beta*(InD[s] +ID[s]+ IdT[s])/N[s])*X[s] - mu*X[s]
dXint[s] <- sigma*X[s] - (1-omega)*(c[s]*beta*(InD[s] +ID[s]+ IdT[s])/N[s])*Xint[s] - mu*Xprep[s]
dInD[s] <- (c[s]*beta*(InD[s] +ID[s]+ IdT[s])/N[s])*X[s] - psi*InD[s]- mu*InD[s]
dID[s] <- (1-omega)*(c[s]*beta*(InD[s] +ID[s]+ IdT[s]) /N[s])*Xint[s]+ psi*InD[s]- mu*ID[s]
N[s] <- X[s]+Xint[s]+InD[s]+ID[s]
diffs <- c(dX[s], dXint[s], dInD[s], dID[s], N[s])}
return(list(diffs))
})}
#Defining parameter and initial values
par <- c(mu=0.033, sigma=0.29, beta=0.40, c=c(2, 30), Ctot=1773600, N=c(332550, 36950), psi=0.022, omega=0.44)
init <- c(X=c(332550,36950), Xint=c(0,0), InD=c(1,1), ID=c(0,0))
t <- seq(0, 30, by=0.1)
#Numerical solution#
Hom.sol <- lsoda(init, t, Dyn,par)
I think you are mixing up parameters and variables. N seems to be defined as a parameter par with dimension 2. However, in your model definition you are updating N with dimension 1.

Error only when running whole block of code

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
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!

Resources