r - 使用索引来引用 dplyr 中 summarise() 中的列 - R

标签 r indexing dplyr

我想用它的索引而不是它的名称来引用 dplyr 中 summarise() 中的一列。例如:

        > a

           id visit timepoint bedroom  den
            1   0     0        62      NA 
            2   1     0        53    6.00  
            3   2     0        56    2.75   
            4   0     1        55      NA 
            5   1     2        61      NA 
            6   2     0        54      NA 
            7   0     1        58    2.75   
            8   1     2        59      NA 
            9   2     2        60      NA 
            10  0     1        57      NA 

           # E.g. 
           a %>% group_by(visit) %>% summarise(avg.bedroom = mean(bedroom, na.rm   =T)
           # Returns
        visit avg.dedroom
        <dbl>       <dbl>
     1     0       4.375
     2     1       2.750
     3     2         NaN

如何在汇总子句中使用“卧室”列的索引而不是其名称?我试过:
     a %>% group_by(visit) %>% summarise("4" = mean(.[[4]], na.rm = T))

但这返回了错误的结果:
       visit      `4`
        <dbl>    <dbl>
      1     0 3.833333
      2     1 3.833333
      3     2 3.833333

我的目标是否可以实现,如果是,如何实现?谢谢你。

最佳答案

也许不完全是您要找的,但一种选择是使用 purrr而不是 dplyr .就像是

# Read in data
d <- read.table(textConnection(" id visit timepoint bedroom  den
        1  12     0        62      NA 
        2  14     0        53    6.00  
        3  14     0        56    2.75   
        4  14     1        55      NA 
        5  14     2        61      NA 
        6  15     0        54      NA 
        7  15     1        58    2.75   
        8  16     2        59      NA 
        9  16     2        60      NA 
        10 17     1        57      NA "), 
    header = TRUE)


library(purrr)

d %>% 
    split(.$timepoint) %>% 
    map_dbl(function(x) mean(x[ ,5], na.rm = TRUE))

#     0     1     2 
# 4.375 2.750   NaN 

或者,与基地
aggregate(d[ ,5] ~ timepoint, data = d, mean)

#   timepoint d[, 5]
# 1         0  4.375
# 2         1  2.750

关于r - 使用索引来引用 dplyr 中 summarise() 中的列 - R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40476410/

相关文章:

r - 如何通过do函数在特定列中拆分不同数量的字符串

python - 在没有双 iloc 的情况下拆分奇数行的 DataFrame

R dplyr : how to use . .. with summary(across()) when ... 将引用数据中的变量名称?

r - R 中带有子集的 For 循环

r - 基于不同的列子集和聚合原始数据表

r - RStudio在启动时为空-没有窗口,没有菜单,没有渲染

sql-server - SQL Server : ~2000 Heap Tables all using GUID Uniqueidentifier - Possible Clustered Indexing?

oracle - 如何索引具有空值的日期列?

r - 如何检查同一列中较早的值中是否存在某个值?

r - 使用 R 的 Bootstrap 问题