简体   繁体   中英

use function in sapply R

I need to create an histogram with the function in #2, someone have an idea? i get the warning message: In hist(as.integer(project.timeV)): NAs introduced by coercion

#1.
roundNorm <- function(m, sd) { #m is Mean, sd is Standard Deviation
  x <- rnorm(1,m,sd)
  roundUp.X <- ceiling(x)
  return(roundUp.X)
}

#2.
project <- function(x) { # route 1: A-B-C-F, route 2: A-D-E-F
  a.time <- roundNorm(10,3)
  b.time <- roundNorm(10,3)
  c.time <- 5
  d.time <- 10
  e.time <- roundNorm(5,2)
  f.time <- 4
  if(b.time+c.time > d.time+e.time){
    projectLength <- a.time+b.time+c.time+f.time
    criRoute <- "A,B,C,F"
    answer <- c(projectLength,criRoute)
  }
  else {
    projectLength <- a.time+d.time+e.time+f.time
    criRoute <- "A,D,E,F"
    answer <- c(projectLength,criRoute)
  }
  return(answer)
}

#3.
samp <- 1:10000
project.timeV <- sapply(samp,project)
hist(as.integer(project.timeV))

If I do this, I get no errors.

project.timeV <- sapply(samp, project, simplify = FALSE)
project.timeV <- do.call(rbind, project.timeV)
hist(as.integer(project.timeV[, 1]))

Here is a preview of what the result looks like. Notice that I do not want sapply to simplify my result. This is something I do with do.call because I want to flatten by rows, not columns.

> head(project.timeV)
     [,1] [,2]     
[1,] "34" "A,D,E,F"
[2,] "34" "A,B,C,F"
[3,] "26" "A,D,E,F"
[4,] "24" "A,B,C,F"
[5,] "29" "A,D,E,F"
[6,] "30" "A,D,E,F"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM