Error in coxModelFrame.coxph(object) : invalid object set x=TRUE in the call to coxph - survival-analysis

The following example is for anyone who is building a Cox Proportional Hazards models and trying to produce prediction error curves, but get an error stating:
Error in coxModelFrame.coxph(object) : invalid object
set x=TRUE in the call to coxph.
Here is the code to reproduce the error:
LIBRARIES
library(survival)
library(survminer)
library(pec)
library(Hmisc)
library(rms)
library(riskRegression)
#install.packages("doMC", repos="http://R-Forge.R-project.org")
library(doMC)
The Data
#Load and store the data
lcOrig <- read.csv("cancer.csv")
#Replace all the 1's with 0's (censored)
lcOrig$status <- gsub(pattern = "1", replacement = "0", x = lcOrig$status, fixed = TRUE)
#Replace all the 2's with 1's (death)
lcOrig$status <- gsub (pattern = "2", replacement = "1", x = lcOrig$status, fixed = TRUE)
#Do the same thing for sex (0 = Males, 1 = Females)
lcOrig$sex <- gsub(pattern = "1", replacement = "0", x = lcOrig$sex, fixed = TRUE)
lcOrig$sex <- gsub(pattern = "2", replacement = "1", x = lcOrig$sex, fixed = TRUE)
#Change the class of these variables to integer.
lcOrig$status <- as.integer(lcOrig$status)
lcOrig$sex <- as.integer(lcOrig$sex)
lcOrig$ph.ecog <- as.integer(lcOrig$ph.ecog)
#Remove missing values and column with over 20% missing data.
apply(lcOrig, 2, function(x) sum(is.na(x))/length(x))
lcOrig <- lcOrig[, c(1:9, 11)]
lc <- lcOrig[complete.cases(lcOrig), ]
Cox Proportional Hazards
fitform1 <- Surv(time, status) ~ inst + age + sex + ph.ecog + ph.karno + pat.karno + wt.loss
cox1 <- coxph(fitform1, data = lc)
PREDICTION ERROR CURVES
extends <- function(...) TRUE
library("doMC")
registerDoMC()
set.seed(0692)
fitpec1 <- pec(list("CPH" = cox1), data = lc, formula = fitform1, splitMethod = "cv10", B = 5, keep.index = TRUE, keep.matrix = TRUE)
The last line of code results in the following error:
Error in coxModelFrame.coxph(object) : invalid object
set x=TRUE in the call to coxph

SOLUTION
Change:
cox1 <- coxph(fitform1, data = lc)
To:
cox1 <- coxph(fitform1, data = lc, x = TRUE)
This did not use to be a requirement 2 years ago, but is now. I hope this helps save you some time!

Related

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit

getting marginal effect post-estimation for nested logit using R mlogit package

I have estimated nested logit in R using the mlogit package. However, I encountered some problems when trying to estimate the marginal effect. Below is the code I implemented.
library(mlogit)
# data
data2 = read.csv(file = "neat_num_energy.csv")
new_ener2 <- mlogit.data(
data2,
choice="alter4", shape="long",
alt.var="energy_altern",chid.var="id")
# estimate model
nest2 <- mlogit(
alter4 ~ expendmaint + expendnegy |
educ + sex + ppa_power_sp + hu_price_powersupply +
hu_2price +hu_3price + hu_9price + hu_10price +
hu_11price + hu_12price,
data = data2,
nests = list(
Trad = c('Biomas_Trad', 'Solar_Trad'),
modern = c('Biomas_Modern', 'Solar_Modern')
), unscaled=FALSE)
# create Z variable
z3 <- with(data2, data.frame(
expendnegy = tapply(expendnegy, idx(nest2,2), mean),
expendmaint= tapply(expendmaint, idx(nest2,2), mean),
educ= mean(educ),
sex = mean(sex),
hu_price_powersupply = mean(hu_price_powersupply),
ppa_power_sp = mean(ppa_power_sp),
hu_2price = mean(hu_2price),
hu_3price = mean(hu_3price),
hu_9price = mean(hu_9price),
hu_10price = mean(hu_10price),
hu_11price = mean(hu_11price),
ppa_power_sp = mean(ppa_power_sp),
hu_12price = mean(hu_12price)
))
effects(nest2, covariate = "sex", data = z3, type = "ar")
#> ** Error in Solve.default (H, g[!fixed]): Lapack routine dgesv: #> system is exactly singular:U[6,6] =0.**
My data is in long format with expendmaint and expendnegy being the only alternative specific while every other variable is case specific.
altern4 is a nominal variable representing each alternative

SymPy : Cancel out unnecessary variables and coefficients

I have an expression like :
b = IndexedBase('b')
k = IndexedBase('k')
w = IndexedBase('w')
r = IndexedBase('r')
z = IndexedBase('z')
i = symbols("i", cls=Idx)
omega = symbols("omega", cls=Idx)
e_p = (-k[i, omega]*r[i]/w[i] + k[i, omega]*r[i]/(b[omega]*w[i]))**b[omega]*k[i, omega]*r[i]/(-b[omega]*k[i, omega]*k[i, omega]**b[omega]*r[i]*z[omega]/w[i] + k[i, omega]*k[i, omega]**b[omega]*r[i]*z[omega]/w[i])
e_p = simplify(e_p)
print(type(e_p))
print(e_p)
<class 'sympy.core.mul.Mul'>
-(-(b[omega] - 1)*k[i, omega]*r[i]/(b[omega]*w[i]))**b[omega]*k[i, omega]**(-b[omega])*w[i]/((b[omega] - 1)*z[omega])
So k[i, omega] should be canceled out when I use simplify() function but do nothing. How can I get rid of unnecessary variables and coefficients?

Lua splitting a string without separators

Is there an easy way to split a string like this:
M34a79 or M2ab943 or M4c4
into
M,34,a,79 or M,2,ab,943 or M,4,c,4
without any separators?
You can do it with a pair of gsub calls:
x = "M34a79 or M2ab943 or M4c4"
x, _ = x:gsub( "(%d)(%a)", "%1,%2" )
x, _ = x:gsub( "(%a)(%d)", "%1,%2" )
print( x )
M,34,a,79 or M,2,ab,943 or M,4,c,4
Might not work in all cases, but does work on your example.
If you don’t mind using the LPEG
library:
local lpeg = require "lpeg"
local C, Ct, P, R = lpeg.C, lpeg.Ct, lpeg.P, lpeg.R
local lpegmatch = lpeg.match
local extract
do
local digit = R"09"
local lower = R"az"
local comma = P","
local space = P" "
local schema = Ct( C(P"M")
* (digit^1 / tonumber)
* C(lower^1)
* (digit^1 / tonumber))
local extractor = Ct((schema + 1)^0)
extract = function (str)
return lpegmatch (extractor, str)
end
end
This will match all sequences of characters of the input
that consist of (in that order)
the letter M,
a sequence of 1 or more decimal digits,
a sequence of 1 or more lowercase characters, and
another sequence of 1 or more decimal digits.
When processing the input each match is put in a subtable,
the digits are converted to Lua numbers on the fly.
Since the question requested it, the leading M is included
in the entries.
Usage example:
local data = extract [[M34a79 or M2ab943 or M4c4]]
for i = 1, #data do
local elm = data[i]
print (string.format ("[%d] = { [1] = %q, [2] = %d, [3] = %q, [4] = %d },",
i, table.unpack (elm)))
end
Output:
[1] = { [1] = "M", [2] = 34, [3] = "a", [4] = 79 },
[2] = { [1] = "M", [2] = 2, [3] = "ab", [4] = 943 },
[3] = { [1] = "M", [2] = 4, [3] = "c", [4] = 4 },
Solution:
http://www.coronalabs.com/blog/2013/04/16/lua-string-magic/
function string:split( inSplitPattern, outResults )
...
end
function val(x)
x = x:gsub( "(%d)(%a)", "%1,%2" )
x = x:gsub( "(%a)(%d)", "%1,%2" )
Table = string.split(x,",")
for i = 1, #Table do
print( Table[i] )
end
end
val("M3a5")
returns M 3 a 5

Use character string as function argument

I'm sure this is simple, but I cannot find a solution ...
I would like to use a variable containing a character string as argument for a function.
x <- c(1:10)
myoptions <- "trim=0, na.rm=FALSE"
Now, something like
foo <- mean(x, myoptions)
should be the same as
foo <- mean(x, trim=0, na.rm=FALSE)
Thanks in advance!
You can use eval and parse:
foo <- eval(parse(text = paste("mean(x,", myoptions, ")")))
A more natural way to do what you want is to use do.call. For example,
R> l[["trim"]] = 0
R> l[["na.rm"]] = FALSE
R> l[["x"]] = 1:10
##Or l <- list(trim = 0, na.rm = FALSE, x = 1:10)
R> do.call(mean, l)
[1] 5.5
If for some reason you really want to use a myoptions string, you could always use strsplit to coarce it into a list form. For example,
R> y = "trim=0, na.rm=FALSE"
R> strsplit(y, ", ")
[[1]]
[1] "trim=0" "na.rm=FALSE"
R> strsplit(y, ", ")[[1]][1]
[1] "trim=0"
Here's a third answer that both uses parse, alist and do.call. My motivation for this new answer, is in the case where arguments are passed interactively from a client-side as chars. Then I guess, there is no good way around not using parse. Suggested solution with strsplit, cannot understand the context whether a comma , means next argument or next argument within an argument. strsplit does not understand context as strsplit is not a parser.
here arguments can be passed as "a=c(2,4), b=3,5" or list("c(a=(2,4)","b=3","5")
#' convert and evaluate a list of char args to a list of arguments
#'
#' #param listOfCharArgs a list of chars
#'
#' #return
#' #export
#'
#' #examples
#' myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
#' myArgs = callMeMaybe(myCharArgs)
#' do.call(mean,myArgs)
callMeMaybe2 = function(listOfCharArgs) {
CharArgs = unlist(listOfCharArgs)
if(is.null(CharArgs)) return(alist())
.out = eval(parse(text = paste0("alist(",
paste(parse(text=CharArgs),collapse = ","),")")))
}
myCharArgs = list('x=c(1:3,NA)',"trim=0","TRUE")
myArgs = callMeMaybe2(myCharArgs)
do.call(mean,myArgs)
[1] 2
Using all of do.call, eval and parse (combining kohske's and csgillespie's answers, and also WoDoSc's answer to 'Pass a comma separated string as a list'):
x <- c(1:10)
myoptions <- "trim = 0, na.rm = FALSE"
do.call(
what = mean,
args = append(list(x = x), eval(parse(text = paste0("list(", myoptions, ")"))))
)
This solution can be quite resilient in a more complex case, such as shown below.
myfn <- function(x, y = 0, z = 0, ...) {
print(paste("x:", x))
print(paste("y:", y))
print(paste("z:", z))
if (length(list(...)) > 0) {
print("other:")
print(list(...))
}
}
myextraargs <- paste(
"y = c(11, 14), z = 47,",
"t = data.frame(p = c('apple', 'plum'), j = c(7, 2), k = c(3, 21))"
)
do.call(
what = myfn,
args = append(
list(x = 7),
eval(parse(text = paste0("list(", myextraargs, ")")))
)
)
results in:
[1] "x: 7"
[1] "y: 11" "y: 14"
[1] "z: 47"
[1] "other:"
$t
p j k
1 apple 7 3
2 plum 2 21
...and...
myextraargs <- NULL
do.call(
what = myfn,
args = append(
list(x = 7),
eval(parse(text = paste0("list(", myextraargs, ")")))
)
)
results in
[1] "x: 7"
[1] "y: 0"
[1] "z: 0"

Resources