R 中跨行和特定列的比例
Proportion across rows and specific columns in R
我想获得一定比例的 pcr 检测并使用以下测试数据集创建一个新列。我想要每一行的检测比例,只在 pcr1 到 pcr6 列中。我希望忽略其他列。
site sample pcr1 pcr2 pcr3 pcr4 pcr5 pcr6
pond 1 1 1 1 1 0 1 1
pond 1 2 1 1 0 0 1 1
pond 1 3 0 0 1 1 1 1
我希望输出创建一个包含比例检测的新列。上面的数据集只是我正在使用的数据集的一小部分。我试过:
data$detection.proportion <- rowMeans(subset(testdf, select = c(pcr1, pcr2, pcr3, pcr4, pcr5, pcr6)), na.rm = TRUE)
这适用于这个小数据集,但我尝试了我的大数据集,但它没有用,它会给出不正确的比例。我正在寻找的是一种方法来计算从 pcr1 到 pcr6 的所有 1,并将它们除以 1 和 0 的总数(我知道是 6,但我希望 R 能够识别它,以防它没有输入)。
我找到了一种方法,以防其他人需要。我不知道这是否最有效,但它对我有用。
data$detection.proportion <- length(subset(testdf, select = c(pcr1, pcr2, pcr3, pcr4, pcr5, pcr6)))
#Calculates the length of pcrs = 6
p.detection <- rowSums(data[,c(-1, -2, -3, -10)] == "1")
#Counts the occurrences of 1 (which is detection) for each row
data$detection.proportion <- p.detection/data$detection.proportion
#Divides the occurrences by the total number of pcrs to find the detected proportion.
我想获得一定比例的 pcr 检测并使用以下测试数据集创建一个新列。我想要每一行的检测比例,只在 pcr1 到 pcr6 列中。我希望忽略其他列。
site sample pcr1 pcr2 pcr3 pcr4 pcr5 pcr6
pond 1 1 1 1 1 0 1 1
pond 1 2 1 1 0 0 1 1
pond 1 3 0 0 1 1 1 1
我希望输出创建一个包含比例检测的新列。上面的数据集只是我正在使用的数据集的一小部分。我试过:
data$detection.proportion <- rowMeans(subset(testdf, select = c(pcr1, pcr2, pcr3, pcr4, pcr5, pcr6)), na.rm = TRUE)
这适用于这个小数据集,但我尝试了我的大数据集,但它没有用,它会给出不正确的比例。我正在寻找的是一种方法来计算从 pcr1 到 pcr6 的所有 1,并将它们除以 1 和 0 的总数(我知道是 6,但我希望 R 能够识别它,以防它没有输入)。
我找到了一种方法,以防其他人需要。我不知道这是否最有效,但它对我有用。
data$detection.proportion <- length(subset(testdf, select = c(pcr1, pcr2, pcr3, pcr4, pcr5, pcr6)))
#Calculates the length of pcrs = 6
p.detection <- rowSums(data[,c(-1, -2, -3, -10)] == "1")
#Counts the occurrences of 1 (which is detection) for each row
data$detection.proportion <- p.detection/data$detection.proportion
#Divides the occurrences by the total number of pcrs to find the detected proportion.