我有一个测试数据
test_data <- as.data.frame(list(
Drugs = c(1, 2, 2, 2, 1, 2, 2, 3, 2, 2, 2, 2, 2, 2, 1, 3, 2, 1, 1, 2, 3, 3, 2, 3, 1, 2, 2, 2, 2, 2, 3, 3, 2, 2, 2, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 2, 2, 1, 2, 2, 2, 2, 3, 1, 3, 1, 1, 2, 1, 2, 2, 1, 3, 1, 1, 3, 3, 2, 1, 3, 2, 2, 3, 1, 3, 2, 1, 2, 3, 1, 2, 3, 2, 1, 3, 1, 2, 3, 3, 2, 3, 2, 2, 2, 3, 1, 2, 2, 3),
Result = c(1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 2, 1, 2, 2, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1, 1, 1, 2, 2, 1)
))
我需要编写一个函数,在计算最大标准化残差后返回一个字符串向量。该网站说我必须在返回整数向量时返回字符串向量。当我在我的 R 中执行我的函数时,它返回一个字符串向量,我不知道发生了什么。这是功能:
maxre <- function(x){
x$Drugs <- factor(x$Drugs, labels = c('drug_1', 'drug_2','drug_3'))
x$Result <- factor(x$Result, labels = c('negative', 'positive'))
zz <- table(x)
res <- chisq.test(zz)
tab <- res$stdres
tab <- as.data.frame(tab)
tab$Drugs <- factor(tab$Drugs, labels = c('drug_1', 'drug_2','drug_3'))
tab$Result <- factor(tab$Result, labels = c('negative', 'positive'))
tab2 <- as.data.frame(tab)
maximal <- max(tab2$Freq)
interm <- tab[tab$Freq == maximal,]
result <- c(interm[1, 1], interm[1, 2])
result <- as.vector(result)
return(result)
}
答案是
[1] "drug_3" "negative"
在R 4.1.0的更新日志中:
使用
将一个因素与其他因素组合现在给出一个因素,当组合具有相同水平的有序因素时,一个有序因素。c()
R 4.1.0
c(factor('a'), factor('b'))
# [1] a b
# Levels: a b
R 4.1.0
c(factor('a'), factor('b'))
# [1] 1 1
您可以将因子列转换为字符,然后再将它们与
c()
组合。
interm[1:2] <- lapply(interm[1:2], as.character)