Jj Blevins
Jj Blevins

Reputation: 395

How to extract a formula or specific function from a package in R?

I am using the R package "pt" to calculate the cummulative prospect theory value.

The first input is the following:

choice_ids <- c(1, 1, 1, 1, 2, 2, 2, 2)
gamble_ids <- c(1, 1, 1, 2, 1, 1, 2, 2)
outcome_ids <- c(1, 2, 3, 1, 1, 2, 1, 2)
objective_consequences <- c(2500, 2400, 0, 2400,2500, 0, 2400, 0)
probability_strings <- c("0.33", "0.66", "0.01", "1.0","0.33", "0.67", "0.34", "0.66")

my_choices <- Choices(choice_ids=choice_ids,gamble_ids=gamble_ids,outcome_ids=outcome_ids,objective_consequences=objective_consequences,probability_strings=probability_strings)

Afterwards

tk_1992_utility <- Utility(fun="power", par=c(alpha=0.88, beta=0.88, lambda=2.25))
linear_in_log_odds_prob_weight <- ProbWeight(fun="linear_in_log_odds", par=c(alpha=0.61, beta=0.724))

comparePT(my_choices,prob_weight_for_positive_outcomes=linear_in_log_odds_prob_weight,prob_weight_for_negative_outcomes=linear_in_log_odds_prob_weight,utility=tk_1992_utility, digits=4)
##   cid gid   ev    pt    ce                 rp
## 1   1   1 2409 881.3  2222                187
## 2   1   2 2400 943.2  2400 -0.000000000001819
## 3   2   1  825 312.6 684.2              140.8
## 4   2   2  816 307.2 670.9              145.1

The comparePT comands hase the pt value as output but also quite a lot of other values. However, I would like to only have the pt value as output, is this somehow possible? I looked into the package but could not find the formula in there, unfortunately.

Upvotes: 1

Views: 489

Answers (1)

AkselA
AkselA

Reputation: 8836

Appears pt is taken off CRAN, but can be installed from the github archive:

library(devtools)
install_github("cran/pt")

comparePT() is an S4 function. Inspecting these are a little different from the regular S3 kind. First you use showMethods() to see the available methods, before you use getMethod() for the method you are interested in.

showMethods("comparePT")
# Function: comparePT (package pt)
# object="Choices"

getMethod("comparePT", "Choices")
# Method Definition:
# 
# function ...

However, the output from comparePT() is just a regular data.frame, so you can subset it by using $ as normal. And wrap as.numeric() around it, as its coded as character.

as.numeric(comparePT(my_choices, linear_in_log_odds_prob_weight, 
                     linear_in_log_odds_prob_weight, tk_1992_utility, 4)$pt)
# [1] 881.3 943.2 312.6 307.2

Upvotes: 1

Related Questions