我正在尝试计算每一列中特定值的出现频率。
基本上,我正在研究不同的细菌分离株(由每行代表)对不同抗生素(代表每列)的治疗的反应。"1“表示该分离株对抗生素具有抵抗力,而"0”表示该分离株对抗生素敏感。
antibiotic1 <- c(1, 1, 0, 1, 0, 1, NA, 0, 1)
antibiotic2 <- c(0, 0, NA, 0, 1, 1, 0, 0, 0)
antibiotic3 <- c(0, 1, 1, 0, 0, NA, 1, 0, 0)
ab <- data.frame(antibiotic1, antibiotic2, antibiotic3)
ab
antibiotic1 antibiotic2 antibiotic3
1 1 0 0
2 1 0 1
3 0 NA 1
4 1 0 0
5 0 1 0
6 1 1 NA
7 NA 0 1
8 0 0 0
9 1 0 0所以看第一行,分离株1对抗生素1具有抵抗力,对抗生素2敏感,对抗生素3敏感。
我想计算一下对每种抗生素都有抵抗力的菌株。即对每一列中的“1”的数量求和,并除以每一列中的分离物的数量(从我的分母中排除NAs )。
我知道如何计数:
apply(ab, 2, count)
$antibiotic1
x freq
1 0 3
2 1 5
3 NA 1
$antibiotic2
x freq
1 0 6
2 1 2
3 NA 1
$antibiotic3
x freq
1 0 5
2 1 3
3 NA 1但我的实际数据集包含许多不同的抗生素和数百个分离物,因此我希望能够同时对所有列运行一个函数,以生成一个数据帧。
我试过了
counts <- ldply(ab, function(x) sum(x=="1")/(sum(x=="1") + sum(x=="0")))但这会产生NAs:
.id V1
1 antibiotic1 NA
2 antibiotic2 NA
3 antibiotic3 NA我也尝试过:
library(dplyr)
ab %>%
summarise_each(n = n())) %>%
mutate(prop.resis = n/sum(n))但是会得到一条错误消息,内容是:
Error in n() : This function should not be called directly任何建议都将不胜感激。
发布于 2016-01-26 16:56:31
我只需要使用colMeans将其矢量化
colMeans(ab, na.rm = TRUE)
# antibiotic1 antibiotic2 antibiotic3
# 0.625 0.250 0.375 顺便说一句,这可以很容易地推广到计算任何数字的频率。例如,如果要在所有列中查找数字2的频率,可以简单地修改为colMeans(ab == 2, na.rm = TRUE)
或者类似地,只是(这避免了矩阵转换与按列求值的权衡)
sapply(ab, mean, na.rm = TRUE)
# antibiotic1 antibiotic2 antibiotic3
# 0.625 0.250 0.375发布于 2016-01-26 16:47:30
这个问题的另一个答案是,这是你想要的吗?
antibiotic1 <- c(1, 1, 0, 1, 0, 1, NA, 0, 1)
antibiotic2 <- c(0, 0, NA, 0, 1, 1, 0, 0, 0)
antibiotic3 <- c(0, 1, 1, 0, 0, NA, 1, 0, 0)
ab <- data.frame(antibiotic1, antibiotic2, antibiotic3)
result <- vector()
for (i in 1:dim(ab)[2]) {
print(sum(ab[i],na.rm = TRUE)/dim(na.omit(ab[i]))[1])
result <- c(result,sum(ab[i],na.rm = TRUE)/dim(na.omit(ab[i]))[1])
}
result
0.625 0.250 0.375发布于 2016-01-26 16:48:11
这里有一种方法:
antibiotic1 antibiotic2 antibiotic3
1 0 0
1 0 1
0 NA 1
1 0 0
0 1 0
1 1 NA
NA 0 1
0 0 0
1 0 0
dat <- read.table(file="clipboard",header=T)
sapply(dat, function(x) prop.table(table(x,useNA = "no"))[[2]])
antibiotic1 antibiotic2 antibiotic3
0.625 0.250 0.375 https://stackoverflow.com/questions/35009551
复制相似问题