函数不仅返回值,还返回因子级别?

时间:2016-01-26 20:24:46

标签: r output

这是我困惑的问题。我有一个医院质量数据框架。我在这里使用的变量看起来像这样:

str(ff)
'data.frame':   4706 obs. of  7 variables:
$ Provider.Number                                           : Factor w/4706 levels "010001","010005",..: 1 2 3 4 5 6 7 8 9 10 ...
$ Hospital.Name                                             : Factor w/ 4510 levels "ABBEVILLE AREA MEDICAL CENTER",..: 3587 2150 1048 2506 838 2149 3828 910 3490 465 ...
$ City                                                      : Factor w/ 2926 levels "ABBEVILLE","ABERDEEN",..: 698 269 870 1910 1511 1064 241 900 19 241 ...
$ State                                                     : Factor w/ 54 levels "AK","AL","AR",..: 2 2 2 2 2 2 2 2 2 2 ...
$ Hospital.30.Day.Death..Mortality..Rates.from.Heart.Attack : num  14.3 18.5 18.1 NA NA NA 17.7 18 15.9 NA ...
$ Hospital.30.Day.Death..Mortality..Rates.from.Heart.Failure: num  11.4 15.2 11.3 13.6 13.8 12.5 10.9 16.6 13.6 NA ...
$ Hospital.30.Day.Death..Mortality..Rates.from.Pneumonia    : num  10.9 13.9 13.4 14.9 15.8 8.7 16.2 15.8 10.7 NA ...

我在R中写了一个函数,它应该返回该州最好的医院(死亡率最低)。这是这个功能:

best <- function(state, outcome) {
data <- read.csv("outcome-of-care-measures.csv", na.strings = "Not     Available")
if (state %in% data$State == FALSE) stop("invalid state")
if (outcome == "heart attack") i = 11
else if (outcome == "heart failure") i = 17
else if (outcome == "pneumonia") i = 23
else stop("invalid outcome")
x <- subset(data, data$State == state)
best_h <- x[which.min(x[,i]), ]
best_h[1,2]
}

它工作并返回正确的结果,输出如下:

best("MD", "
[1] GREATER BALTIMORE MEDICAL CENTER
4510 Levels: ABBEVILLE AREA MEDICAL CENTER ... ZUNI COMPREHENSIVE COMMUNITY HEALTH CENTER

问题是 - 如何摆脱输出中的4510 Levels...

1 个答案:

答案 0 :(得分:1)

您可以使用as.character(best_h[1,2])转换为角色向量。