Error: argument - shiny

I'm trying to create a histogram of density and I'm having the error: argument 'x' must be numeric. I tried to use (as.numeric(input$d)) instead of just d but got the same error. Does anyone know how to solve this?
server.R
output$hist <- renderPlot({
input$action
if(is.null(input$action))
return(NULL)
else
isolate({
trees3 <- FindTreesCHM(chm(), (as.numeric(input$fws)), (as.numeric(input$minht)))
d <- density(trees3["height"])
plot(d, xlab = "Height", ylab = "Density", main = "")
polygon((as.numeric(input$d)), col = "darkseagreen")
})
})
Thank you a lot! :)

I think that the problem is in d <- density(trees3["height"]). The first argument of the density function is x and it should be numeric. You are using [] instead of [[]]. [] return the list of elements and [[]] return the single element on the list. So just try changing
d <- density(trees3["height"])
with
d <- density(trees3[["height"]]).
Also, I don't think you need the else in your code. But if you need to use an if...else statement make sure that:
It is important to note that else must be in the same line as the closing braces of the if statements. http://www.programiz.com/r-programming/if-else-statement

Related

How to knit out table codes into table in R markdown

I am a basic-level learner of R. I am having a problem knitting out tables with a code my professor designed for the students. The code for table designs is set as below. I put this in my R markdown as below.
```{r, results="hide", message=FALSE, warning = FALSE, error = FALSE}
## my style latex summary of regression
jhp_report <- function(...){
output <- capture.output(stargazer(..., omit.stat=c("f", "ser")))
# The first three lines are the ones we want to remove...
output <- output[4:length(output)]
# cat out the results - this is essentially just what stargazer does too
cat(paste(output, collapse = "\n"), "\n")
}
```
After this, I tried printing this out with knitr.
```{r, message=FALSE, warning = FALSE, error = FALSE}
set.seed(1973)
N <- 100
x <- runif(N, 6, 20)
D <- rbinom(N, 1, .5)
t <- 1 + 0.5*x - .4*D + rnorm(N)
df.lm <- data.frame(y = y, x =x, D =D)
df.lm$D <- factor(df.lm$D, labels = c('Male', 'Female'))
##REGRESSION
reg.parallel <- lm(y ~ x + D, data = df.lm)
jhp_report(reg.parallel, title = "Result", label = "tab:D", dep.var.labels = "$y$")
```
As a result, instead of a table, it keeps on showing only the pure codes. I would like to know how I have to set up R markdown for it to print out the table instead of the codes. This is how the result looks like when I knit it.
I expected that there must be some setup options to print the table out. But I couldn't find the right one. Also, my assignment for class requires students to use this code. I did find other options like knitr::kable but I would like to use the given code for this assignment.
Thank you in advance!

In R: "regcomp error: 'Missing ')'" --' regexec problems

product <- c('Model1','Model2','Model3')
price <- c(NA, NA, NA)
pricelist <- data.frame(product, price)
Using this data frame I run the following for loop to scan a document(called unformatted text in the code below) for the price and insert the price into the data frame
for (i in 1:nrow(pricelist))
{
p <- regexec( paste(pricelist[i,1], "(.*?)", "([0-9]+\\.[0-9][0-9])", sep = ""), unformattedtext)
p2 <- regmatches(unformattedtext, p)
p3 <- sapply(p2, function(x) x[3])
pricelist[i,2] <- p3
}
If I run this loop I get an error with regexec saying this-> regcomp error: 'Missing ')''
BUT if insert the values for i manually, using the exact same code, it functions correctly. Any idea on what I'm doing wrong? If it matters I'm using plyr for rbind.fill to get those NAs in my initial data frame.

Function to subset dataframe using pattern list argument

I have a pattern list
patternlist <- list('one' = paste(c('a','b','c'),collapse="|"), 'two' = paste(1:5,collapse="|"), 'three' = paste(c('k','l','m'),collapse="|"))
that I want to select from to extract rows from a data frame
dataframez <- data.frame('letters' = c('a','b','c'), 'numbers' = 1:3, 'otherletters' = c('k','l','m'))
with this function
pattern.record <- function(x, column="letters", value="one")
{
if (column %in% names(x))
{
result <- x[grep(patternlist$value, x$column, ignore.case=T),]
}
else
{
result <- NA
}
return(result)
}
oddly enough, I get an error when I run it:
> pattern.record(dataframez)
Error in grep(patternlist$value, x$column, ignore.case = T) :
invalid 'pattern' argument
The problem is your use of the `$` operator.
In your function, it is looking a column \ named element called column
It is far simpler here to use `[[`
Then x[[column]] uses what column is defined as, not column as a name.
The relevant lines in ?`$` are
Both [[ and $ select a single element of the list. The main difference is that $ does not allow computed indices, whereas [[ does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of [[ can be controlled using the exact argument.
You are trying to use value and column as computed indices (i.e. computing what value and column are defined as), thus you need `[[`.
The function becomes
pattern.record <- function(x, column="letters", value="one", pattern_list)
{
if (column %in% names(x))
{
result <- x[grep(pattern_list[[value]], x[[column]], ignore.case=T),]
}
else
{
result <- NA
}
return(result)
}
pattern.record(dataframez, patternlist = pattern_list)
## letters numbers otherletters
## 1 a 1 k
## 2 b 2 l
## 3 c 3 m
note that I've also added an argumentpattern_list so it does not depend on an object named patternlist existing somewhere in the parent environments (in your case the global environment.

Can one add a data.frame to itself?

I want to append or add a data.frame to itself...
Much in the same way the one adds:
n <- n + t
I have a function that creates a data.frame.
I have been using:
g <- function(compareA,compareB) {
for (i in 1:1000) {
ttr <- t.test(compareA, compareA, var.equal = TRUE)
tt_pvalues[i] <- ttr$p.value
}
name_tag <- paste(nameA, nameB, sep = "_Vs_")
tt_titles <- data.frame(name_tag, tt_titles)
# character vector which I want to add to a list
ALL_pvalues <- data.frame(tt_pvalues, ALL_pvalues)
# adding a numeric vector of values to a larger data.frame
}
Would cbind be better here?
There are two methods that would "add or append" data to a data.frame by columns and one that would append by rows. Assuming tag is the data.frame, and tt_titles is a vector of the same length that 'tag' has rows, then either of these would work:
tag <- cbind(tag, tt_titles)
# tt_titles could also be a data.frame with same number of rows
Or:
tag[["tt_titles"]] <- tt_titles
Now let's assume that we have instead two data.frames with the same column.names:
bigger.df <- rbind(tag, tag2)

Why does my unit test run successfully in the R console but returns an error with "make test"?

I am learning how to develop an R package. Everything goes well, thanks to the R manuals and this wiki for RUnit. More precisely, when I launch my unit tests within a new R console, all tests finish successfully:
#rm(list=ls())
library(RUnit)
testSuite <- defineTestSuite("current", "~/src/mypkg/inst/unitTests/")
isValidTestSuite # returns TRUE
runTestSuite(testSuite) # returns Number of errors: 0 and Number of failures: 0
However, when I launch them in a terminal, I got one error (the function in question uses the package GenomicRanges that I installed in "~/src/Rlibs"):
$ make test R_LIBS="~/src/Rlibs/"
...
ERROR in test.MyFunction: Error in match(x, table, nomatch = 0L) :
'match' requires vector arguments
I don't see what is causing this error. I guess you will need more info about the code and the test, but it's not easy because I don't know how to replicate this error on a small example without making a new package just for this. Maybe some of you will have an idea about this error message and give me some hints?
Edit: to help someone to give me a hint on the error, here is the code I wrote for a dummy package. The aim is to find which items of "p" are included within items of "g".
Here is the test:
test.MyFunction <- function(){
g <- list(c1=data.frame(name=c("g1","g2"), start=c(11,1111),
end=c(500,1500), strand=c("+","+"), stringsAsFactors=FALSE))
p <- list(c1=data.frame(name=c("p1","p2"), strand=c("+","-"),
start=c(11,601), end=c(20, 610), stringsAsFactors=FALSE))
exp <- list(c1=list(g1=c("p1"))) # item "p1" is included in item "g1"
obs <- MyFunction(g, p)
checkEquals(obs, exp)
}
And here is the function itself:
MyFunction <- function(g, p){
res <- lapply(names(g), function(c.name){
res.c <- list()
nb.g <- length(g[[c.name]]$name)
if(length(.find.package("GenomicRanges", quiet=TRUE)) > 0){
g.ranges <- GRanges(seqnames=Rle(c(c.name), c(nb.g)),
ranges=IRanges(g[[c.name]]$start,
g[[c.name]]$end, names=g[[c.name]]$name),
strand="*")
p.ranges <- GRanges(seqnames=Rle(c(c.name), nrow(p[[c.name]])),
ranges=IRanges(p[[c.name]]$start,
p[[c.name]]$end, names=p[[c.name]]$name),
strand=p[[c.name]]$strand)
for(g.name in names(g.ranges)){
links <- p.ranges %in% g.ranges[names(g.ranges) == g.name]
if(sum(links) > 0)
res.c[[g.name]] <- names(p.ranges)[which(links)]
}
} else{
msg <- "can't find package GenomicRanges"
stop(msg, call.=FALSE)
}
res.c
})
names(res) <- names(g)
return(res)
}
I think this line is your culprit:
links <- p.ranges %in% g.ranges[names(g.ranges) == g.name].
%in% is match, and that is what the error message seems to be reading:
ERROR in test.MyFunction: Error in match(x, table, nomatch = 0L) :
'match' requires vector arguments
There is something about p.ranges and g.ranges that it doesn't like. I.e., they can't be coerced to vectors OR you're not subsetting properly and the object type is incorrect ([ or [[).