组合因子时返回字符串向量而不是整数向量

标签 r chi-squared r-factor

我有测试数据

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"

最佳答案

问题源自以下行:

result <- c(interm[1, 1], interm[1, 2])

其中 interterm 的第一列和第二列都是因子。

changelog R 4.1.0:

Using c() to combine a factor with other factors now gives a factor, an ordered factor when combining ordered factors with identical levels.

  • 版本>=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)

关于组合因子时返回字符串向量而不是整数向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75883443/

相关文章:

r - case_when 与部分字符串匹配和 contains()

python - Python中卡方检验统计量的P值

r - 将 `mutate` 数据帧变量转换为因子时指定级别

R - 聚合因子/字符变量

r - 使多个数据帧的因子水平保持一致的最佳方法

r - 方面ggplot2的内部排序

r - R 中的二项式 TreeMap

r - 带有字符串标签的颜色条指南,例如 "low - medium - high"

python - 带有 log.p 参数的 Python 中 R 的 qchisq?

python - 计算用于卡方检验的先前机会图