我在 R 中工作,我想对与我的一个因素变量 service 相关的不同变量进行相关性分析。我真的不知道该怎么做。我看过融合和转置,但这些功能都没有给我我需要的格式。我在想我需要将因子向量拆分为单个向量(对应于每个服务级别),然后以某种方式获取一个数值变量(例如 sumofcases)成为新创建的服务向量的观察值。因此,一种服务水平是住院治疗,另一种是病例管理。然后,我将有一个称为“住院”的向量和另一个称为“病例管理”的向量,每列中的观察结果将是“病例总数”的相应值。然后我可以运行两个服务向量之间的关联。那么,这将导致创建大量数据框(如果它有效,那就没问题了)。
这是示例数据:
Year Region Service SumofCases
2010 10 Hospitalization 324
2011 1 Case Management 200
我希望它看起来像:
Year Region Hospitalization Case Management
2010 10 200 NA
2011 1 NA 324
我认为相关函数内部也可能有一些东西可以让我在一个因子的水平之间运行相关性,但到目前为止我还没有发现任何东西。
@Thomas,回应您的回答:
我认为这绝对是朝着正确的方向发展,但我该如何处理不均匀的因素水平呢?
我运行了这段代码:
tmp<-MIC$Service levels(tmp)
levels(tmp)<-c("Ancillary Services", rep("Health Services",2))
cor(as.numeric(tmp),MIC$SumofCases)`
并得到以下错误:
Error in levels<-.factor`(*tmp*, value = c("Ancillary Services", "Health Services", : >number of levels differs > cor(as.numeric(tmp),MIC$SumofCases) [1] NA`
运行输出dput(head(MIC))
:
dput(head(MIC))
structure(list(FY = structure(c(6L, 1L, 1L, 1L, 1L, 1L), .Label = c("2006",
"2007", "2008", "2009", "2010", "2011"), class = "factor"), Region =
structure(c(1L,4L, 6L, 6L, 9L, 2L), .Label = c("1", "10", "2", "3", "4", "5","6", "7",
"8", "9"), class = "factor"), SumofCases = c(0,1, 1, 2, 11, 14), Service =
structure(c(17L, 4L, 4L, 4L,4L, 4L), .Label = c("Ancillary Services", "Behavioral
Treatment","Care Coordination", "Community Living Supports", "Crisis Services",
"Dental", "ECT", "Employment Services", "Equipment", "Family Services", "Fiscal
Intermediary Services", "Health Services", "Hospitalization", "Medication",
"Monitoring", "OT/PT/SLT", "Other", "Peer Services", "Prevention", "Residential
Treatment", "Respite", "Screening & Assessment", "Therapy", "Transportation"), class =
"factor")), .Names = c("FY", "Region", "SumofCases", "Service"),
row.names = c(NA,6L), class = "data.frame")
运行以下代码后,我得到了 cor 函数的 NA 。
tmp<-MIC$Service
levels(tmp)
levels(tmp)<-c("Ancillary Services","Behavioral Treatment","Care Coordination",
"Community Living Supports","Crisis Services","Dental","ECT","Employment Services",
"Equipment","Family Services",
"Fiscal Intermediary Services","Health Services",
"Hospitalization","Medication",
"Monitoring","OT/PT/SLT",
"Other","Peer Services",
"Prevention", "Residential Treatment",
"Respite","Screening & Assessment",
"Therapy","Transportation")
cor(as.numeric(tmp),MIC$SumofCases)
输出:
> cor(as.numeric(tmp),MIC$SumofCases)
[1] NA