I'm not sure I understand the type of variable I'm working with. It's the result of a binary classifier:
> mod_binary$predictions %>% glimpse()
num [1:10000, 1:2] 0.989 0.904 0.99 0.989 0.989 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:2] "FALSE" "TRUE"
> mod_binary$predictions %>% head()
FALSE TRUE
[1,] 0.9894592 0.01054078
[2,] 0.9044349 0.09556509
[3,] 0.9898756 0.01012441
[4,] 0.9888804 0.01111959
[5,] 0.9890123 0.01098766
[6,] 0.9641537 0.03584634
What is this variable type called? A list? A named list? A named vector?
I would like to retrieve a vector of the TRUE predictions. Tried:
> mod_binary$predictions$TRUE
Error: unexpected numeric constant in "mod_binary$predictions$TRUE"
> mod_binary$predictions[["TRUE"]]
Error in mod_binary$predictions[["TRUE"]] : subscript out of bounds
> mod_binary$predictions[[1]]
[1] 0.9894592
That last one returned a single observation, and actually the wrong one. It's the FALSE prediction (see the call to head() above)
How can I get just a vector of predicted probabilities for TRUE?
It looks like a matrix from the attributes showed in the glimpse and also from the printed format of the data especially the row names ([1,]). So, the $ won't work for extraction.
According to ?Extract
The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
mod_binary$predictions[, "TRUE"]
Related
I got this error while merging 1 column from 1 df called data.all to the my working dfcalled data
setDT(data)[setDT(data.all), RX_HOSP_SURG_APPR_2010 := i.RX_HOSP_SURG_APPR_2010, on=c("PUF_CASE_ID","SR_ID" )]
Warning message: In [.data.table(setDT(data), setDT(data.all),
:=(RX_HOSP_SURG_APPR_2010, : Coerced double RHS to logical to
match the type of the target column (column 157 named
'RX_HOSP_SURG_APPR_2010'). If the target column's type logical is
correct, it's best for efficiency to avoid the coercion and create the
RHS as type logical. To achieve that consider R's type postfix:
typeof(0L) vs typeof(0), and typeof(NA) vs typeof(NA_integer_) vs
typeof(NA_real_). You can wrap the RHS with as.logical() to avoid this
warning, but that will still perform the coercion. If the target
column's type is not correct, it's best to revisit where the DT was
created and fix the column type there; e.g., by using colClasses= in
fread(). Otherwise, you can change the column type now by plonking a
new column (of the desired type) over the top of it; e.g. DT[,
RX_HOSP_SURG_APPR_2010:=as.double(RX_HOSP_SURG_APPR_2010)]. If the
RHS of := has nrow(DT) elements then the assignment is called a column
plonk and is the way to change a column's type. Column types can be
observed with sapply(DT,typeof) [... truncated]
I tried different ways but I could not figure this out
str(data$RX_HOSP_SURG_APPR_2010)
logi [1:8671] FALSE FALSE FALSE NA NA NA ...
str(data.all$RX_HOSP_SURG_APPR_2010)
'haven_labelled' num [1:129296] 0 0 NA NA NA NA NA NA NA NA ...
- attr(, "label")= chr "Surgical Approach at this Facility 2010 and Later"
- attr(, "format.spss")= chr "F1.0"
- attr(, "display_width")= int 23
- attr(, "labels")= Named num [1:7] 0 1 2 3 4 5 9 ..- attr(*, "names")= chr [1:7] "No surgical procedure of primary site" "Robotic
assisted" "Robotic converted to open" "Laparoscopic" ...
Any advice will be appreciated.
You could share dput(head(data)) and dput(head(data.all)) of your "gigantic" data. Please improve your question.
In order to assing on the fly during the join, you need both column classes to be the same and, as you noticed, your variable in data is logical (probably because at the time you read it from a file it only had zeros and NAs) while your variable in data.all is a weird class.
You can try to assign the class first with:
class(data$RX_HOSP_SURG_APPR_2010) <- class(data.all$RX_HOSP_SURG_APPR_2010)
I have two objects of class 'times' generated using chron that I am trying to compare. On the surface they look identical:
> str(x)
Class 'times' atomic [1:6] 0.04444 0.05417 0.05486 0.00208 0.01111 ...
..- attr(*, "format")= chr "h:m:s"
> str(y)
Class 'times' atomic [1:6] 0.04444 0.05417 0.05486 0.00208 0.01111 ...
..- attr(*, "format")= chr "h:m:s"
So I expected that x - y = 0 or x==y would return TRUE, but this is not the case:
> x-y
[1] -6.245005e-17 -2.775558e-17 -2.775558e-17 7.372575e-18 -7.112366e-17 0.000000e+00
> x==y
[1] FALSE FALSE FALSE FALSE FALSE TRUE
Any idea what is going on or how I can compare the two? I already tried changing it to POSIXct and that works, but before comparing, I have operations to do on the data frame columns this data comes from (adding and subtracting), which can't be done with POSIXct. Also, it requires extra steps and this is meant to be a quick check up to see if there are any discrepencies in the data.
I guess I can use as.character(x)==as.character(y), and it works, but there has to be a more elegant way of doing this...
I want to first calculate a markov transition matrix and then take exponent of it. To achieve the first goal I use the markovchainFit function inside markovchain package and it return me a data.frame , rather than a matrix. So I need to convert it to matrix before I take exponent.
My R code snippet is like
#################################
# Estimate Transition Matrix #
#################################
setwd("G:/Data_backup/GDP_per_Capita")
library("foreign")
library("Hmisc")
mydata <- stata.get("G:/Data_backup/GDP_per_Capita/states.dta")
mydata
library(markovchain)
library(expm)
rgdp_e=mydata[,2:7]
rgdp_o=mydata[,8:13]
createSequenceMatrix(rgdp_e)
rgdp_e_trans<-markovchainFit(data=rgdp_e,,method="bootstrap",nboot=5, name="Bootstrap Mc")
rgdp_e_trans<-as.numeric(unlist(rgdp_e_trans))
rgdp_e_trans<-as.matrix(rgdp_e_trans)
is.matrix(rgdp_e_trans)
rgdp_e_trans %^% 1/5
the rgdp_e_trans is a data frame, and I try to convert it to a numeric matrix. It seems work when I test it using is.matrix command. However, the final line give me an error said
Error in rgdp_e_trans %^% 2 :
(list) object cannot be coerced to type 'double'
After some searching work in stackoverflow, I find this question sharing the similar problem and use rgdp_e_trans<-as.numeric(unlist(rgdp_e_trans)) to coerce the object to be `double', but it seems not work.
Besides, the data.frame rgdp_e_trans contains no factor or characters
The output in the console is like
> rgdp_e=mydata[,2:7]
> rgdp_o=mydata[,8:13]
> createSequenceMatrix(rgdp_e)
Error: not compatible with STRSXP
> rgdp_e_trans<-markovchainFit(data=rgdp_e,,method="bootstrap",nboot=5, name="Bootstrap Mc")
> rgdp_e_trans
$estimate
1 2 3 4 5
1 0.6172840 0.18930041 0.09053498 0.074074074 0.02880658
2 0.1125828 0.59602649 0.28476821 0.006622517 0.00000000
3 0.0000000 0.03846154 0.60256410 0.358974359 0.00000000
4 0.0000000 0.01162791 0.03488372 0.691860465 0.26162791
5 0.0000000 0.00000000 0.00000000 0.044247788 0.95575221
> rgdp_e_trans<-as.numeric(unlist(rgdp_e_trans))
Error: (list) object cannot be coerced to type 'double'
> rgdp_e_trans<-as.matrix(rgdp_e_trans)
> is.matrix(rgdp_e_trans)
[1] TRUE
> rgdp_e_trans %^% 1/5
Error in rgdp_e_trans %^% 1 :
(list) object cannot be coerced to type 'double'
>
Any suggestion to fix the problem, or alternative way to calculate the exponent ? Thank you.
Additional:
> str(rgdp_e_trans)
List of 1
$ estimate:Formal class 'markovchain' [package "markovchain"] with 4 slots
.. ..# states : chr [1:5] "1" "2" "3" "4" ...
.. ..# byrow : logi TRUE
.. ..# transitionMatrix: num [1:5, 1:5] 0.617 0.113 0 0 0 ...
.. .. ..- attr(*, "dimnames")=List of 2
.. .. .. ..$ : chr [1:5] "1" "2" "3" "4" ...
.. .. .. ..$ : chr [1:5] "1" "2" "3" "4" ...
.. ..# name : chr "Bootstrap Mc"
and I comment out the as.matrix part
rgdp_e=mydata[,2:7]
rgdp_o=mydata[,8:13]
createSequenceMatrix(rgdp_e)
rgdp_e_trans<-markovchainFit(data=rgdp_e,,method="bootstrap",nboot=5, name="Bootstrap Mc")
rgdp_e_trans
str(rgdp_e_trans)
# rgdp_e_trans<-as.numeric(unlist(rgdp_e_trans))
# rgdp_e_trans<-as.matrix(rgdp_e_trans)
# is.matrix(rgdp_e_trans)
rgdp_e_trans$estimate %^% 1/5
You can access the transition matrix directly from the object returned by markovchainFit as:
rgdp_e_trans$estimate#transitionMatrix
Here rgdp_e_trans is your return value from markovchainFit, which is actually a list containing the information from the fitting process. You access the estimates item of that list by using the $ operator. The estimate object is from a formal S4 class (see e.g. Advanced R by Hadley Wickham for a description of the object systems used in R), which is why in order to access its items you have to use the # operator instead of the standard $ used for the more common S3 objects.
If you print out the return value of as.matrix(rgdp_e_trans) it should be immediately obvious where your initial approach went wrong. In general it's a good idea to check the structure of an object with the str function - instead of relying on its print method - when you encounter unexpected results or are working with new types of objects.
Browse[1]> lmc
[[1]]
t test of coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.0090841 0.0063588 1.4286 0.154840
m[, "FX_RET_28"] 0.1122490 0.1599463 0.7018 0.483705
m[, "FX_RET_42"] 0.1702606 0.1041854 1.6342 0.103944
m[, "FX_RET_51"] -0.4735956 0.2450406 -1.9327 0.054823 .
m[, "FX_RET_52"] 0.2475292 0.1458240 1.6975 0.091321 .
m[, "FX_RET_53"] -0.5569527 0.1945823 -2.8623 0.004699 **
m[, "FX_RET_60"] -0.3191905 0.2887157 -1.1056 0.270379
---
Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
Browse[1]> str(lmc)
List of 1
$ : coeftest [1:7, 1:4] 0.00908 0.11225 0.17026 -0.4736 0.24753 ...
..- attr(*, "dimnames")=List of 2
.. ..$ : chr [1:7] "(Intercept)" "m[, \"FX_RET_28\"]" "m[, \"FX_RET_42\"]" "m[, \"FX_RET_51\"]" ...
.. ..$ : chr [1:4] "Estimate" "Std. Error" "t value" "Pr(>|t|)"
..- attr(*, "method")= chr "t test of coefficients"
I want to pull out the Estimate column into a vector with (Intercept), m[, "FX_RE_28"], etc. as the names of the elements. I would appreciate any help.
Thanks
From the str output, one would predict that the values for the Estimate-column could be extracted with one of four incantations:
lmc[[1]][ , 1] # using just numerical indexing ... OR
# Apparently not this: lmc[['coeftest']][ , "Estimate" ] # Using character/name indexing
From the comments it appears that there was no name of the list element. Appears the "coeftest" is not a name but rather the class-type of the first (and only=) item in that list.
I thought (but was wrong) : The reason that lmc[[1]]$coeftest[,1] offered by RichAtMango fails is that the object is a list and lmc[[1]] delivers the first and only item of the list which is a matrix. This would have worked: lmc[1]$coeftest[,1] , because the [.]-function delivers a sublist (rather than the value itself) and it still would have had an element named 'coeftest'.
If you had wanted a one column matrix (which would display with the rownames on the side) then the call would have been:
lmc[['coeftest']][ , "Estimate" , drop=FALSE] # to avoid returning as a vector
You cannot "accept" comments as answers in SO. It's not clear why MichaelChirico didn't post an answer. He may have been too busy to post something he thought was sufficiently developed or maybe he wanted to to post dput(lmc) so he could offer a tested answer. I thought the downvote you got was unfair, since you did provide enough information to answer and the indexing difference between "[" and "[[" can be difficult to get for persons beginning with R. Your request needed understanding of both the indexing of lists and the indexing of R matrices.
I can't really create a code example because I'm not quite sure what the problem is and my actual problem is rather involved. That said it seems like kind of a generic problem that maybe somebody's seen before.
Basically I'm constructing 3 different dataframes and rbinding them together, which is all as expected smooth sailing but when I try to write that merged frame back to the DB I get this error:
Error in .External2(C_writetable, x, file, nrow(x), p, rnames, sep, eol, :
unimplemented type 'list' in 'EncodeElement'
I've tried manually coercing them using as.data.frame() before and after the rbinds and the returned object (the same one that fails to write with the above error message) exists in the environment as class data.frame so why does dbWriteTable not seem to have got the memo?
Sorry, I'm connecting to a MySQL DB using RMySQL. The problem I think as I look a little closer and try to explain myself is that the columns of my data frame are themselves lists (of the same length), which sorta makes sense of the error. I'd think (or like to think anyways) that a call to as.data.frame() would take care of that but I guess not?
A portion of my str() since it's long looks like:
.. [list output truncated]
$ stcong :List of 29809
..$ : int 3
..$ : int 8
..$ : int 4
..$ : int 2
I guess I'm wondering if there's an easy way to force this coercion?
Hard to say for sure, since you provided so little concrete information, but this would be one way to convert a list column to an atomic vector column:
> d <- data.frame(x = 1:5)
> d$y <- as.list(letters[1:5])
> str(d)
'data.frame': 5 obs. of 2 variables:
$ x: int 1 2 3 4 5
$ y:List of 5
..$ : chr "a"
..$ : chr "b"
..$ : chr "c"
..$ : chr "d"
..$ : chr "e"
> d$y <- unlist(d$y)
> str(d)
'data.frame': 5 obs. of 2 variables:
$ x: int 1 2 3 4 5
$ y: chr "a" "b" "c" "d" ...
This assumes that each element of your list column is only a length one vector. If any aren't, things will be more complicated, and you'd likely need to rethink your data structure anyhow.