Posts

Showing posts with the label R

Converting A Quosure To A String In R

Answer : We can use quo_name print(paste("looking at", quo_name(thing))) quo_name does not work if the quosure is too long: > q <- quo(a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z) > quo_name(q) [1] "+..." rlang::quo_text (not exported by dplyr ) works better, but introduces line breaks (which can be controlled with parameter width ): > rlang::quo_text(q) [1] "a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + \n q + r + s + t + u + v + w + x + y + z" Otherwise, as.character can also be used, but returns a vector of length two. The second part is what you want: > as.character(q) [1] "~" [2] "a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q + r + s + t + u + v + w + x + y + z" > as.character(q)[2] [1] "a + b + c + d + e + ...

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 ...

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(...

Converting Multiple Columns From Character To Numeric Format In R

Answer : You could try DF <- data.frame("a" = as.character(0:5), "b" = paste(0:5, ".1", sep = ""), "c" = letters[1:6], stringsAsFactors = FALSE) # Check columns classes sapply(DF, class) # a b c # "character" "character" "character" cols.num <- c("a","b") DF[cols.num] <- sapply(DF[cols.num],as.numeric) sapply(DF, class) # a b c # "numeric" "numeric" "character" If you're already using the tidyverse, there are a few solution depending on the exact situation. Basic if you know it's all numbers and doesn't have NAs library(dplyr) # solution dataset %>% mutate_if(is.character,as.numeric) Test cases df <- data.frame( x1 = c('1','2','3'), x2 = c('4','5','6'), x3 = c(...

Converting Between Matrix Subscripts And Linear Indices (like Ind2sub/sub2ind In Matlab)

Answer : This is not something I've used before, but according to this handy dandy Matlab to R cheat sheet, you might try something like this, where m is the number of rows in the matrix, r and c are row and column numbers respectively, and ind the linear index: MATLAB: [r,c] = ind2sub(size(A), ind) R: r = ((ind-1) %% m) + 1 c = floor((ind-1) / m) + 1 MATLAB: ind = sub2ind(size(A), r, c) R: ind = (c-1)*m + r For higher dimension arrays, there is the arrayInd function. > abc <- array(dim=c(10,5,5)) > arrayInd(12,dim(abc)) dim1 dim2 dim3 [1,] 2 2 1 You mostly don't need those functions in R. In Matlab you need those because you can't do e.g. A(i, j) = x where i,j,x are three vectors of row and column indices and x contains the corresponding values. (see also this question) In R you can simply: A[ cbind(i, j) ] <- x

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...

Converting Two Columns Of A Data Frame To A Named Vector

Answer : Use the names function: whatyouwant <- as.character(dd$name) names(whatyouwant) <- dd$crit as.character is necessary, because data.frame and read.table turn characters into factors with default settings. If you want a one-liner: whatyouwant <- setNames(as.character(dd$name), dd$crit) You can also use deframe(x) from the tibble package for this. tibble::deframe() It converts the first column to names and second column to values. You can make a vector from dd$name , and add names using names() , but you can do it all in one step with structure() : whatiwant <- structure(as.character(dd$name), names = as.character(dd$crit))