我有569行与乳腺癌有关的数据。在A列中,每行细胞中的值为'M‘或'B’(恶性或良性)。在B列中,给出了每个肿瘤细胞核的凹度。我想分别找出所有恶性肿瘤和所有良性肿瘤的平均凹度。
编辑:作为示例给出的A和B列的前25行
> df2
data2.diagnosis data2.concavity_mean
1 M 0.3001000
2 M 0.0869000
3 M 0.1974000
4 M 0.2414000
5 M 0.1980000
6 M 0.1578000
7 M 0.1127000
8 M 0.0936600
9 M 0.1859000
10 M 0.2273000
11 M 0.0329900
12 M 0.0995400
13 M 0.2065000
14 M 0.0993800
15 M 0.2128000
16 M 0.1639000
17 M 0.0739500
18 M 0.1722000
19 M 0.1479000
20 B 0.0666400
21 B 0.0456800
22 B 0.0295600
23 M 0.2077000
24 M 0.1097000
25 M 0.1525000我如何要求R给我“B列中的行的平均值,A列中的值是M”,然后“给出它们在A列中的值是B"?
发布于 2022-01-16 18:22:00
假设变量A是一个因素,示例dataframe example的基本R方法将是
example <- data.frame(A = as.factor(c('M','B','M', 'B')), B=c(1,2,3,4))
mean(example$B[example$A == 'M'])
#> [1] 2
# for both factor levels simultaneously you can use
by(example$B, example$A, mean)
#> example$A: B
#> [1] 3
# ---- #
#> example$A: M
#> [1] 2请注意。由reprex包在2022-01-16上创建(v2.0.1)
发布于 2022-01-16 19:50:15
复制上述用户的一个示例(他们提供了有效的解决方案),我只是提供了一些使用tidyverse包的替代解决方案。
example <- data.frame(A = as.factor(c('M','B','M', 'B')), B=c(1,2,3,4))
#first example creates a new table with summarized values
example %>% #takes your data table
group_by(A) %>% #groups it by the factors listed in column A
summarize(mean_A=mean(B)) #finds the mean of each subgroup (from previous step)如果您发现这些答案中的任何一个是有用的,请选择它作为最终答案。
发布于 2022-01-16 18:27:52
正如注释中指出的那样,最好有一个可重复的示例和您的数据(或者至少是其中的一个子集)来查看您正在处理的是什么。
无论如何,您的问题的解决方案应该如下所示(我正在使用模拟数据):
set.seed(1986)
dta = data.frame("type" = c(rep("B", length = 5), rep("M", length = 5)), "nucleus" = rnorm(10))
mean(dta$nucleus[dta$type == "B"]) # Mean concavity for benign.
mean(dta$nucleus[dta$type == "M"]) # Mean concavity for malign.基本上,我只是将mean()函数应用于数据的两个子集,方法是使用[]运算符选择行。
编辑
现在我们已经了解了您的实际数据,我可以提供一个完整的解决方案:
mean(dta$data2.concavity_mean[dta$data2.diagnosis== "B"]) # Mean concavity for benign.
mean(dta$data2.concavity_mean[dta$data2.diagnosis== "M"]) # Mean concavity for malign.https://stackoverflow.com/questions/70732836
复制相似问题