【问题标题】:how to calculate the mean of a specific column respect to specific variables in R [duplicate]如何计算特定列相对于R中特定变量的平均值[重复]
【发布时间】:2017-01-19 15:43:42
【问题描述】:

这是我的示例数据集。

Name    Type    B     C     D
Carl    AB      1     0     2
Carl    AB      5     4     1 
Joe     B       0     3     1
Joe     O       2     1     0
Joe     B       4     4     2 

我的目标是将 B 列的平均值计算为如下函数:someFunction(Name,Type)

例如,someFunction(Carl,AB) = 3someFunction(Joe,B) = 2

有人知道我会怎么做吗?

【问题讨论】:

  • 对于这种特殊情况,可能不需要函数。您只需输入:mean(dat$B[dat$Name == "Joe"])

标签: r average multiple-columns


【解决方案1】:

我们可以使用函数根据函数参数中输入的字符串获取B的子集,然后得到mean

f1 <- function(str1, str2){
        mean(subset(dat, Name == str1 & Type ==str2, select = B)[,1])
 }

f1("Carl", "AB")
#[1] 3

f1("Joe", "B")
#[1] 2

更新

如果我们需要将mean 列名也作为参数,

f2 <- function(str1, str2, meanCol){
     mean(dat[dat$Name ==str1 & dat$Type == str2, meanCol])
}

f2("Carl", "AB", "B")
#[1] 3

数据

dat <- structure(list(Name = c("Carl", "Carl", "Joe", "Joe", "Joe"), 
Type = c("AB", "AB", "B", "O", "B"), B = c(1L, 5L, 0L, 2L, 
4L), C = c(0L, 4L, 3L, 1L, 4L), D = c(2L, 1L, 1L, 0L, 2L)),
 .Names = c("Name", 
"Type", "B", "C", "D"), class = "data.frame", row.names = c(NA, 
-5L))

【讨论】:

  • 谢谢。这给了我一个答案,我认为它太高了,您的代码中的 [,1] 是什么意思?
  • @Amanda 我以为您想要一个具体的答案。(基于您之前对另一个问题的评论)。 [,1] 只是将 data.frame 列子集化为一个向量,因为 mean 仅适用于 vector 而不适用于 data.frame
  • 嗯,这是否意味着如果我想获得 c 列而不是 b 列的平均值,这会改变 [,1] 吗?
  • @Amanda 这是基于您在帖子中的函数中显示的参数。如果您想让列也是动态的,请再添加一个参数。 [,1] 用于将一列的“data.frame”转换为向量
  • 谢谢。如果我的列有负值,在除以总计数(以求均值)之前,这些值是否会正确相加?
【解决方案2】:

这会计算 NameType 的唯一组合的平均值:

dat %>% group_by(Name, Type) %>% summarise(mn = mean(B))
Source: local data frame [3 x 3]
Groups: Name [?]

   Name  Type    mn
  <chr> <chr> <dbl>
1  Carl    AB     3
2   Joe     B     2
3   Joe     O     2

从这里你可以得到你需要的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    相关资源
    最近更新 更多