【问题标题】:Mean of One Column based of Level of other Column(s) in Loops循环中基于其他列的级别的一列的平均值)
【发布时间】:2011-10-17 03:00:36
【问题描述】:

根据每个因素(在这种情况下为 C1 到 C4)取 mf 的最后一列 (C5) 的平均值,如果数据文件不同,因此无需更改任何内容,它应该自动修改,因为我们将使用循环来分配名称和计算。

结果会像 级别为 1 时 C1 的平均值为 5.5 级别为 2 时 C1 的平均值为 3.5 级别为 1 时 C2 的平均值为 6.5 级别为 2 时 C2 的平均值为 2.5 级别为 1 时 C3 的平均值为 4 级别为 2 时 C3 的平均值为 5

我想做一个通用程序,所以当我们更改数据时,程序不会发生变化,总和将基于新数据。新数据中的因子和水平不会发生变化。

# call excel file containing orthogonal profile
pf <- read.csv(file="pfile2.csv",head=FALSE,sep=",") 
# call excel file response / data 
rs <- read.csv(file="respf2.csv",head=FALSE,sep=",")
# Merge orthogonal arrays  and response in a single file
mf= merge(pf, rs, by="V1")
# Change the name of the new file/merge file all column contain word Cx
names(mf)<-sprintf("C%d",1:length(mf))
# total variable and total data 
tc=NCOL(mf)
tr=NROW(mf)
pf
  V1 V2 V3 V4
1  1  1  1  1
2  2  1  1  2
3  3  1  2  1
4  4  1  2  2
5  5  2  1  1
6  6  2  1  2
7  7  2  2  1
8  8  2  2  2

rs
   V1 V2
1  1  8
2  2  7
3  3  4
4  4  3
5  5  6
6  6  5
7  7  2
8  8  1

mf
   C1 C2 C3 C4 C5
1  1  1  1  1  8
2  2  1  1  2  7
3  3  1  2  1  4
4  4  1  2  2  3
5  5  2  1  1  6
6  6  2  1  2  5
7  7  2  2  1  2
8  8  2  2  2  1

tc
[1] 5
tr
[1] 8

【问题讨论】:

  • 下次提示,您可以使用 dput(mf) 然后将输出粘贴到您的问题中。这样人们就可以轻松地复制和粘贴它并处理您的实际数据。

标签: r


【解决方案1】:

非常简单,无需加载任何其他包即可完成。

aggregate(C5 ~ C2, mf, mean)
aggregate(C5 ~ C3, mf, mean)
aggregate(C5 ~ C4, mf, mean)

应该可以带你到那里。没有测试,因为没有时间输入您的数据,请参阅我对您问题的评论。

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多