Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
唯一和级别之间的差异以及suppresswarnings的用法_R - Fatal编程技术网

唯一和级别之间的差异以及suppresswarnings的用法

唯一和级别之间的差异以及suppresswarnings的用法,r,R,我现在正在Coursera上学习R编程入门课程,我的代码中有以下疑问。下面是我的一段代码 rankall <- function(outcome, num = "best") { ## Read outcome data dat <- read.csv("outcome-of-care-measures.csv") ## Check that outcome are valid outcomeValues <- c("heart attack", "h

我现在正在Coursera上学习R编程入门课程,我的代码中有以下疑问。下面是我的一段代码

 rankall <- function(outcome, num = "best") {

  ## Read outcome data
  dat <- read.csv("outcome-of-care-measures.csv")





## Check that outcome are valid
  outcomeValues <- c("heart attack", "heart failure", "pneumonia")

  if(!(outcome %in% outcomeValues)){
    stop("invalid outcome")


    }

  column <- if(outcome == "heart attack"){
    11
  }
  else if(outcome == "heart failure"){
    17
  }
  else if(outcome == "pneumonia") {
    23
  }

  dat[, column] <- suppressWarnings(as.numeric(levels(dat[, column])[dat[, column]]))
  dat[, 2] <- as.character(dat[, 2])
  dat[, 11] <- as.numeric(dat[, 11]) # heart attack
  dat[, 17] <- as.numeric(dat[, 17]) # heart failure
  dat[, 23] <- as.numeric(dat[, 23]) # pneumonia
  output <- vector()
  states <- levels(dat[, 7])

  ## Return hospital name in that state with lowest 30-day death rate
  ## For each state, find the hospital of the given rank
  for( i in 1:length(states)){




 stateData <- dat[grep(states[i], dat$State), ]
  outcomeData <- stateData[order(stateData[, column], stateData[, 2], na.last = NA), ]
  hospital <- if(num == "best" || num == 1){
    outcomeData[1, 2]
  }
  else if(num == "worst") {
    outcomeData[nrow(outcomeData), 2]
  }
  else {
    outcomeData[num, 2]
  }
  result <- append(result, c(hospital, states[i]))
  }




## Return a data frame with the hospital names and the (abbreviated) state name
  result <- as.data.frame(matrix(result, nrow = length(states), ncol = 2, byrow = TRUE))
  colnames(result) <- c("Hospital names", "State")


  result
  }

rankall因为因子列的级别可能比实际值高,例如:

x <- factor(1:3, levels = 1:4)
x
# [1] 1 2 3
# Levels: 1 2 3 4

unique(x)
# [1] 1 2 3
# Levels: 1 2 3 4
length(unique(x))
# [1] 3

levels(x)
# [1] "1" "2" "3" "4"
length(levels(x))
# [1] 4
x您能
dput(head(dat))吗?这将使您更容易遵循代码。
x <- factor(1:3, levels = 1:4)
x
# [1] 1 2 3
# Levels: 1 2 3 4

unique(x)
# [1] 1 2 3
# Levels: 1 2 3 4
length(unique(x))
# [1] 3

levels(x)
# [1] "1" "2" "3" "4"
length(levels(x))
# [1] 4