Plots lists of data after assagn then in a function - r

I started using R for a course of Computational Fluid Dynamics and one of the starting lessons we should create a function that put out two lists of data. So I wrote this function:
Green.Ampt=function(param){
k=param[1]
Psi=param[2]
DTheta=param[3]
h=param[4]
F1=0.65
F1=0.65
vector.F2<-1:h
vector.f<-1:h
for(tempo in 1 : h){
DeltaF=1
while(DeltaF>0.01) {
F2=k*tempo+Psi*DTheta*log(F1/(Psi*DTheta)+1)
DeltaF=abs(F1-F2)
F1=F2
}
vector.F2[tempo]=F2
vector.f[tempo]= k*(Psi*DTheta/F2+1)}
OUT<-list(vector.F2, vector.f)
return(OUT)
}
I used this Green.Ampt(c(0.65,16.7,0.34,10)) to run the function then I controlled the console have recieved the following output:
[[1]]
[1] 3.152985 4.745484 6.077012 7.284812 8.404389 9.469498
[7] 10.490538 11.474561 12.434380 13.371189`
[[2]]
[1] 1.8205417 1.4277289 1.2573215 1.1566294 1.0891396 1.0397461
[7] 1.0018123 0.9716419 0.9468141 0.9260188`
I want to give at this two series of data a name because I need to plot them, but I am not successful in this.

Save the return value of your function as an object, which in this case will be a list. You can then extract the components of the list using [[ notation in a call to plot:
x <- Green.Ampt(c(0.65,16.7,0.34,10))
plot(x[[1]], x[[2]])
Here's the result:

Related

How does R Markdown automatically format print effects into dataframes? Or how can I access special print methods?

I'm working with the WRS2 package and there are cases where it'll output its analysis (bwtrim) into a list with a special class of the analysis type class = "bwtrim". I can't as.data.frame() it, but I found that there is a custom print method called print.bwtrim associated with it.
As an example let's say this is the output: bwtrim.out <- bwtrim(...). When I run the analysis output in an Rmarkdown chunk, it seems to "steal" part of the text output and make it into a dataframe.
So here's my question, how can I either access print.bwtrim or how does R markdown automatically format certain outputs into dataframes? Because I'd like to take this outputted dataframe and use it for other purposes.
Update: Here is a minimally working example -- put the following in a chunk in Rmd file."
```{r}
library(WRS2)
df <-
data.frame(
subject = rep(c(1:100), each = 2),
group = rep(c("treatment", "control"), each = 2),
timepoint = rep(c("pre", "post"), times = 2),
dv = rnorm(200, mean = 2)
)
analysis <- WRS2::bwtrim(dv ~ group * timepoint,
id = subject,
data = df,
tr = .2)
analysis
```
With this, a data.frame automatically shows up in the chunk afterwards and it shows all the values very nicely. My main question is how can I get this data.frame for my own uses. Because if you do str(analysis), you see that it's a list. If you do class(analysis) you get "bwtrim". if you do methods(class = "bwtrim"), you get the print method. And methods(print) will have a line that says print.bwtrim*. But I can't seem to figure out how to call print.bwtrim myself.
Regarding what Rmarkdown is doing, compare the following
If you run this in a chunk, it actually steals the data.frame part and puts it into a separate figure.
```{r}
capture.output(analysis)
```
However, if you run the same line in the console, the entire output comes out properly. What's also interesting is that if you try to assign it to another object, the output will be stolen before it can be assigned.
Compare x when you run the following in either a chunk or the console.
```{r}
x<-capture.output(analysis)
```
This is what I get from the chunk approach when I call x
[1] "Call:"
[2] "WRS2::bwtrim(formula = dv ~ group * timepoint, id = subject, "
[3] " data = df, tr = 0.2)"
[4] ""
[5] ""
This is what I get when I do it all in the console
[1] "Call:"
[2] "WRS2::bwtrim(formula = dv ~ group * timepoint, id = subject, "
[3] " data = df, tr = 0.2)"
[4] ""
[5] " value df1 df2 p.value"
[6] "group 1.0397 1 56.2774 0.3123"
[7] "timepoint 0.0001 1 57.8269 0.9904"
[8] "group:timepoint 0.5316 1 57.8269 0.4689"
[9] ""
My question is what can I call whatever Rstudio/Rmarkdown is doing to make data.frames, so that I can have an easy data.frame myself?
Update 2: This is probably not a bug, as discussed here https://github.com/rstudio/rmarkdown/issues/1150.
Update 3: You can access the method by using WRS2:::bwtrim(analysis), though I'm still interested in what Rmarkdown is doing.
Update 4: It might not be the case that Rmarkdown is stealing the output and automatically making dataframes from it, as you can see when you call x after you've already captured the output. Looking at WRS2:::print.bwtrim, it prints a dataframe that it creates, which I'm guessing Rmarkdown recognizes then formats it out.
See below for the print.bwtrim.
function (x, ...)
{
cat("Call:\n")
print(x$call)
cat("\n")
dfx <- data.frame(value = c(x$Qa, x$Qb, x$Qab), df1 = c(x$A.df[1],
x$B.df[1], x$AB.df[1]), df2 = c(x$A.df[2], x$B.df[2],
x$AB.df[2]), p.value = c(x$A.p.value, x$B.p.value, x$AB.p.value))
rownames(dfx) <- c(x$varnames[2], x$varnames[3], paste0(x$varnames[2],
":", x$varnames[3]))
dfx <- round(dfx, 4)
print(dfx)
cat("\n")
}
<bytecode: 0x000001f587dc6078>
<environment: namespace:WRS2>
In R Markdown documents, automatic printing is done by knitr::knit_print rather than print. I don't think there's a knit_print.bwtrim method defined, so it will use the default method, which is defined as
function (x, ..., inline = FALSE)
{
if (inline)
x
else normal_print(x)
}
and normal_print will call print().
You are asking why the output is different. I don't see that when I knit the document to html_document, but I do see it with html_notebook. I don't know the details of what is being done, but if you look at https://rmarkdown.rstudio.com/r_notebook_format.html you can see a discussion of "output source functions", which manipulate chunks to produce different output.
The fancy output you're seeing looks a lot like what knitr::knit_print does for a dataframe, so maybe html_notebook is substituting that in place of print.

How to turn each value in a list into a list of lists, made of values from a function

I have a list of >1000 values. dput(head(list)):
list("WP100", "WP106", "WP107", "WP111", "WP117", "WP12")
Function getXrefList from rWikiPathways package produces a new list of associated genes for each WP value.
input: (H parameter gives genes in the external gene format)
library(rWikiPathways)
getXrefList(list[[1]], 'H')
output:
[1] "ANPEP" "G6PD" "GCLC" "GCLM" "GGT1" "GGT5" "GPX1" "GPX2" "GPX3" "GPX4" "GSR" "GSS" "GSTA1"
[14] "GSTA5" "GSTM1" "GSTM2" "GSTT2" "IDH1" "OPLAH"
I would like to turn the original list into a list of lists. The WP value being the ith values and the jth values being the resulting list of genes from getXrefList function.
Current progress:
new_list <- lapply(list, function(x){getXrefList(x, 'H')})
new_list[[1]]
output:
"ANPEP" "G6PD" "GCLC" "GCLM" "GGT1" "GGT5" "GPX1" "GPX2" "GPX3" "GPX4" "GSR" "GSS" "GSTA1" "GSTA5" "GSTM1" "GSTM2" "GSTT2" "IDH1" "OPLAH"
Wheras the ideal output would look something like this:
List
WP100
"ANPEP" "G6PD" "GCLC" "GCLM" "GGT1" "GGT5" "GPX1" "GPX2" "GPX3" "GPX4" "GSR" "GSS" "GSTA1" "GSTA5" "GSTM1" "GSTM2" "GSTT2" "IDH1" "OPLAH"
WP106
"ABAT" "AGXT" "ASL" "ASPA" "ASS1" "DARS" "GAD1" "GAD2" "GOT1" "GOT2" "GPT" "PC"
And so forth in this fashion. Any help would be appreciated.
Solved. Easy fix.
names(new_list) <- list

R - Dynamically Switch Between Variables in a Data Frame?

I have a data frame that has a collection of many zip codes and "city,state" in the US. So for instance it might read (note that the actual data frame has like 25000 observations):
zip.codes = c(33603, 33701, 32835)
place.names = c("Tampa, FL", "Saint Petersburg, FL", "Orlando, FL")
df = data.frame(zip.codes, place.names)
I am using this as part of a Shiny App. I'd like the user to be able to select a zip code, but to only have it return the place name. So if the user inputs 33603, then the code would return "Tampa, FL".
I've tried researching the Switch function to try to do this, but that seems to only accept hard-coded lists (which is kind of a nonstarter with so many entries in the DF). Is there a way to setup the switch function using variables? Otherwise, does anybody have another idea that might work?
First create vectors place.names and zip.codes and then try any of the following alternatives:
place.names <- as.character(df$place.names)
zip.codes <- df$zip.codes
1) match
place.names[match(33603, zip.codes)]
## [1] Tampa, FL
2) logical condition
place.names[33603 == zip.codes]
## [1] Tampa, FL
3) lookup name
v <- setNames(place.names, zip.codes)
unname(v[as.character(33603)])
## [1] Tampa, FL
4) switch
L <- setNames(as.list(place.names), zip.codes)
do.call("switch", c(as.character(33603), L))
## [1] "Tampa, FL"

How to convert a "list" to "EUtilisSUmmary" class in R

I am trying to do a multiple different term search in RISmed package of R as shown below:
library(RISmed)
library(rentrez)
library(dplyr)
search_topic<-c("KRAS AND MEK inhibitor","BRAF AND BRAF inhibitor")
search_query <- lapply((search_topic),EUtilsSummary, retmax=50,
mindate=2000, maxdate=2017)
Search query is a list and my next step here is to get the Pubmed IDs obtained by search term. However, when i try to use get it using
QueryId(search_query)
I get the
error:unable to find an inherited method for function ‘QueryId’ for signature ‘"list"’
I understand QueryID will work on EUtilisSummary class and hence QueryID function is not working. I tried converting it using
as(search_query, "EUtilisSummary", strict=TRUE, ext)
but this fails and the error is:
no method or default for coercing “list” to “EUtilisSummary”.
How do i convert this list object into EUtilisSummary class? Thanks in advance!
lapply returns a list of objects with classes defined by the function called
library(RISmed)
library(rentrez)
library(dplyr)
search_topic <- c("KRAS AND MEK inhibitor","BRAF AND BRAF inhibitor")
search_query <- lapply((search_topic),EUtilsSummary, retmax=50,
mindate=2000, maxdate=2017)
In this case search_query is a list (class(search_query) containing objects of class EUtilsSummary class(search_query[[1]]).
To manipulate such objects in a list one can just use another lapply with a function that can take them as arguments:
lapply(search_query, QueryId)
#output:
[[1]]
[1] "29079711" "29067643" "28982179" "28982154" "28957417" "28938614" "28866094" "28807001" "28797845" "28783173"
[11] "28775144" "28746882" "28619758" "28581516" "28574828" "28554329" "28551618" "28492898" "28459468" "28372922"
[21] "28301591" "28248226" "28215705" "28178529" "28167505" "28154798" "28152546" "28062115" "28060183" "28002807"
[31] "27997540" "27922010" "27876675" "27846317" "27834733" "27822414" "27821484" "27803104" "27793696" "27167191"
[41] "27733477" "27699948" "27670374" "27496137" "27484466" "27469379" "27467210" "27441499" "27422710" "27399335"
[[2]]
[1] "29100459" "29098416" "29096034" "29094484" "29085667" "29084636" "29079332" "29074209" "29072975" "29070145"
[11] "29066909" "29059158" "29054724" "29050517" "29050239" "29050218" "29048432" "29043205" "29040023" "29028954"
[21] "29028788" "28994264" "28991513" "28986666" "28984520" "28984291" "28984141" "28982601" "28982154" "28981385"
[31] "28979142" "28978720" "28976960" "28973166" "28963969" "28963614" "28961465" "28960564" "28959611" "28951457"
[41] "28947956" "28939558" "28936920" "28931905" "28923537" "28923400" "28919996" "28918496" "28915798" "28893027"

Iterating an R Script as a function of sequential survey questions

The function below works perfectly for my purpose. The display is wonderful. Now my problem is I need to be able to do it again, many times, on other variables that fit other patterns.
In this example, I've output results for "q4a", I would like to be able to do it for sequences of questions that follow patterns like: q4 < a - z > or q < 4 - 10 >< a - z >, automagically.
Is there some way to iterate this such that the specified variable (in this case q4a) changes each time?
Here's my function:
require(reshape) # Using it for melt
require(foreign) # Using it for read.spss
d1 <- read.spss(...) ## Read in SPSS file
attach(d1,warn.conflicts=F) ## Attach SPSS data
q4a_08 <- d1[,grep("q4a_",colnames(d1))] ## Pull in everything matching q4a_X
q4a_08 <- melt(q4a_08) ## restructure data for post-hoc
detach(d1)
q4aaov <- aov(formula=value~variable,data=q4a) ## anova
Thanks in advance!
Not sure if this is what you are looking for, but to generate the list of questions:
> gsub('^', 'q', gsub(' ', '',
apply(expand.grid(1:10,letters),1,
function(r) paste(r, sep='', collapse='')
)))
[1] "q1a" "q2a" "q3a" "q4a" "q5a" "q6a" "q7a" "q8a" "q9a" "q10a"
[11] "q1b" "q2b" "q3b" "q4b" "q5b" "q6b" "q7b" "q8b" "q9b" "q10b"
[21] "q1c" "q2c" "q3c" "q4c" "q5c" "q6c" "q7c" "q8c" "q9c" "q10c"
[31] "q1d" "q2d" "q3d" "q4d" "q5d" "q6d" "q7d" "q8d" "q9d" "q10d"
[41] "q1e" "q2e" "q3e" "q4e" "q5e" "q6e" "q7e" "q8e" "q9e" "q10e"
[51] "q1f" "q2f" "q3f" "q4f" "q5f" "q6f" "q7f" "q8f" "q9f" "q10f"
[61] "q1g" "q2g" "q3g" "q4g" "q5g" "q6g" "q7g" "q8g" "q9g" "q10g"
[71] "q1h" "q2h" "q3h" "q4h" "q5h" "q6h" "q7h" "q8h" "q9h" "q10h"
[81] "q1i" "q2i" "q3i" "q4i" "q5i" "q6i" "q7i" "q8i" "q9i" "q10i"
[91] "q1j" "q2j" "q3j" "q4j" "q5j" "q6j" "q7j" "q8j" "q9j" "q10j"
...
And then you turn your inner part of the analysis into a function that takes the question prefix as a parameter:
analyzeQuestion <- function (prefix)
{
q <- d1[,grep(prefix,colnames(d1))] ## Pull in everything matching q4a_X
q <- melt(q) ## restructure data for post-hoc
qaaov <- aov(formula=value~variable,data=q4a) ## anova
return (LTukey(q4aaov,which="",conf.level=0.95)) ## Tukey's post-hoc
}
Now - I'm not sure where your 'q4a' variable is coming from (as used in the aov(..., data=q4a)- so not sure what to do about that bit. But hopefully this helps.
To put the two together you can use sapply() to apply the analyzeQuestion function to each of the prefixes that we automagically generated.
I would recommend melting the entire dataset and then splitting variable into its component pieces. Then you can more easily use subset to look at (e.g.) just question four: subset(molten, q = 4).

Resources