Posts

Showing posts with the label R

Align Multiple Tables Side By Side

Image
Answer : Just put two data frames in a list, e.g. t1 <- head(mtcars)[1:3] t2 <- head(mtcars)[4:6] knitr::kable(list(t1, t2)) Note this requires knitr >= 1.13. I used this Align two data.frames next to each other with knitr? which shows how to do it in html and this https://tex.stackexchange.com/questions/2832/how-can-i-have-two-tables-side-by-side to align 2 Latex tables next to each other. It seems that you cannot freely adjust the lines of the table as you can do it with xtable (does anybody know more about this?). With format = Latex you get a horizontal line after each row. But the documentation shows two examples for other formats. One using the longtable package (additional argument: longtable = TRUE ) and the other using the booktabs package ( booktabs = TRUE ). --- title: "sample" output: pdf_document header-includes: - \usepackage{booktabs} --- ```{r global_options, R.options=knitr::opts_chunk$set(warning=FALSE, message=FALSE)} ``` ```{r s...

Code Folding In Bookdown

Answer : Global Hide/Show button for the entire page To use @Yihui's hint for a button that fold all code in the html output, you need to paste the following code in an external file (I named it header.html here): Edit: I modified function toggle_R so that the button shows Hide Global or Show Global when clicking on it. <script type="text/javascript"> // toggle visibility of R source blocks in R Markdown output function toggle_R() { var x = document.getElementsByClassName('r'); if (x.length == 0) return; function toggle_vis(o) { var d = o.style.display; o.style.display = (d == 'block' || d == '') ? 'none':'block'; } for (i = 0; i < x.length; i++) { var y = x[i]; if (y.tagName.toLowerCase() === 'pre') toggle_vis(y); } var elem = document.getElementById("myButton1"); if (elem.value === "Hide Global") elem.value = "Show Global"; else ...

Cluster Data In Heat Map In R Ggplot

Image
Answer : You can achieve this by defining the order of Timepoints in a dendrogram after you have applied hclust to your data: data <- scale(t(data)) ord <- hclust( dist(data, method = "euclidean"), method = "ward.D" )$order ord [1] 2 3 1 4 8 5 6 10 7 9 The only thing you have to do then is transforming your Time-column to a factor where the factor levels are ordered by ord : pd <- as.data.frame( data ) pd$Time <- sub("_.*", "", rownames(pd)) pd.m <- melt( pd, id.vars = "Time", variable.name = "Gene" ) pd.m$Gene <- factor( pd.m$Gene, levels = colnames(data), labels = seq_along( colnames(data) ) ) pd.m$Time <- factor( pd.m$Time, levels = rownames(data)[ord], labels = c("0h", "0.25h", "0.5h","1h","2h","3h","6h","12h","24h","48h") ) The rest is done by ggplot automatically: ggplot( pd....

Calculating R^2 For A Nonlinear Least Squares Fit

Answer : You just use the lm function to fit a linear model: x = runif(100) y = runif(100) spam = summary(lm(x~y)) > spam$r.squared [1] 0.0008532386 Note that the r squared is not defined for non-linear models, or at least very tricky, quote from R-help: There is a good reason that an nls model fit in R does not provide r-squared - r-squared doesn't make sense for a general nls model. One way of thinking of r-squared is as a comparison of the residual sum of squares for the fitted model to the residual sum of squares for a trivial model that consists of a constant only. You cannot guarantee that this is a comparison of nested models when dealing with an nls model. If the models aren't nested this comparison is not terribly meaningful. So the answer is that you probably don't want to do this in the first place. If you want peer-reviewed evidence, see this article for example; it's not that you can't compute the R^2 valu...

Add A Horizontal Line To Plot And Legend In Ggplot2

Image
Answer : (1) Try this: cutoff <- data.frame( x = c(-Inf, Inf), y = 50, cutoff = factor(50) ) ggplot(the.data, aes( year, value ) ) + geom_point(aes( colour = source )) + geom_smooth(aes( group = 1 )) + geom_line(aes( x, y, linetype = cutoff ), cutoff) (2) Regarding your comment, if you don't want the cutoff listed as a separate legend it would be easier to just label the cutoff line right on the plot: ggplot(the.data, aes( year, value ) ) + geom_point(aes( colour = source )) + geom_smooth(aes( group = 1 )) + geom_hline(yintercept = 50) + annotate("text", min(the.data$year), 50, vjust = -1, label = "Cutoff") Update This seems even better and generalizes to mulitple lines as shown: line.data <- data.frame(yintercept = c(50, 60), Lines = c("lower", "upper")) ggplot(the.data, aes( year, value ) ) + geom_point(aes( colour = source )) + geom_smooth(aes( group ...

Center Plot Title In Ggplot2

Image
Answer : From the release news of ggplot 2.2.0 : "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme : "left-aligned by default". As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title. ggplot() + ggtitle("Default in 2.2.0 is left-aligned") ggplot() + ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") + theme(plot.title = element_text(hjust = 0.5)) As stated in the answer by Henrik, titles are left-aligned by default starting with ggplot 2.2.0. Titles can be centered by adding this to the plot: theme(plot.title = element_text(hjust = 0.5)) However, if you create many plots, it may be tedious to add this line everywhere. One could then also change the default behaviour of ggplot with theme_update(plot.title = element_text(hjust = 0.5)) Once you have run this line, all plots created...

Adding A Linestring By St_read In Shiny/Leaflet

Answer : Your test data is a dead link now, but I had a similar issue trying to plot sf linestrings and polygons in leaflet . The full error was Error in if (length(nms) != n || any(nms == "")) stop("'options' must be a fully named list, or have no names (NULL)") : missing value where TRUE/FALSE needed I was able to successfully plot my geometries by dropping the Z dimension from the line and polygon with st_zm . Here is an example: library(sf) library(leaflet) # create sf linestring with XYZM dimensions badLine <- st_sfc(st_linestring(matrix(1:32, 8)), st_linestring(matrix(1:8, 2))) # check metadata for badLine > head(badLine) Geometry set for 2 features geometry type: LINESTRING dimension: XYZM bbox: xmin: 1 ymin: 3 xmax: 8 ymax: 16 epsg (SRID): NA proj4string: NA LINESTRING ZM (1 9 17 25, 2 10 18 26, 3 11 19 2... LINESTRING ZM (1 3 5 7, 2 4 6 8) # attempt map; will fail > leaflet(...