【发布时间】:2018-10-23 07:54:36
【问题描述】:
我已经创建了一个函数,它可以增加某行中某些列中的值。为此,我编写了一个函数,该函数通过我的数据框进行子集化以找到它需要的行(通过查看性别、年龄、剥夺、然后是合作伙伴的数量),然后将数字添加到我需要的任何列(取决于这些风险因素),然后计算风险(我的代码用于 STI 测试)。
但是,这不会用新值更改我现有的数据框,而是创建一个新变量 patientRow 来保存这些新值。我需要有关如何将其合并到现有数据框中的帮助。谢谢!
adaptRisk <- function(dataframe, sexNum, ageNum, deprivationNum,
partnerNum, testResult){
sexRisk = subset(dataframe, sex == sexNum)
ageRisk = subset(sexRisk, age == ageNum)
depRisk = subset(ageRisk, deprivation == deprivationNum)
patientRow = subset(depRisk, partners == partnerNum)
if (testResult == "positive") {
patientRow$tested <- patientRow$tested + 1
patientRow$infected <- patientRow$infected + 1
}
else if (testResult == "negative") {
patientRow$tested <- patientRow$tested + 1
}
patientRow <- transform(patientRow, risk = infected/tested)
return(patientRow)
}
这是我的数据框的头,给你一个想法:
sex age deprivation partners tested infected risk
1 Female 16-19 1-2 0-1 132 1 0.007575758
2 Female 16-19 1-2 2 25 1 0.040000000
3 Female 16-19 1-2 >=3 30 1 0.033333333
4 Female 16-19 3 0-1 80 2 0.025000000
5 Female 16-19 3 2 12 1 0.083333333
6 Female 16-19 3 >=3 18 1 0.055555556
我的数据的输出是:
structure(list(sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label =
c("Female",
"Male"), class = "factor"), age = structure(c(1L, 1L, 1L, 1L,
1L, 1L), .Label = c("16-19", "20-24", "25-34", "35-44"), class =
"factor"),
deprivation = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("1-2",
"3", "4-5"), class = "factor"), partners = structure(c(2L,
3L, 1L, 2L, 3L, 1L), .Label = c(">=3", "0-1", "2"), class = "factor"),
tested = c(132L, 25L, 30L, 80L, 12L, 18L), infected = c(1L,
1L, 1L, 2L, 1L, 1L), uninfected = c(131L, 24L, 29L, 78L,
11L, 17L), risk = c(0.00757575757575758, 0.04, 0.0333333333333333,
0.025, 0.0833333333333333, 0.0555555555555556)), .Names = c("sex",
"age", "deprivation", "partners", "tested", "infected", "uninfected",
"risk"), row.names = c(NA, 6L), class = "data.frame")
函数调用示例:
adaptRisk(data, "Female", "16-19", 3, 2, "positive")
sex age deprivation partners tested infected uninfected risk
5 Female 16-19 3 2 13 2 11 0.1538462
【问题讨论】:
-
您能创建一个最小的工作示例并添加更多代码吗?您使用哪个语句来运行您的功能。并且 dput(head(yourdataframe)) 会有所帮助。你可以在这里看看我所说的minimal working example 是什么意思
-
您的函数的输出看起来像是一个数据框,其列与原始数据框中的列不匹配。因此,您将遇到问题,因为您正在“合并”两个列不完全匹配的数据框。
-
@phiver 感谢您的回复!我已添加 dput,非常感谢您的帮助!
-
@J.Win。我不明白你的意思?因为通过数据框的子集保留了列,我没有添加/删除任何东西。当我打印 patientRow 时,它与我的数据框是相同的列
标签: r dataframe machine-learning row subset