簡體   English   中英

R dplyr row表示帶過濾器

[英]R dplyr rowMeans with filter

我看過幾篇關於獲取rowMeans類型的mutate結果的帖子。 例如和dplyr-使用像rowmeans()這樣的mutate() ,但是我想讓另一個變量充當過濾器。

我知道該數據不是很整潔,可以將“ f#”和“ d#”變量重新整形,然后轉換為“ f”和“ d”,然后過濾“ f”並匯總“ d”。 但是,有沒有一種方法可以重塑? 我設計了下面的代碼

library(tidyverse)

x<-data.frame(f1=c(1,1), f2=c(1,0), f3=c(1,1),
              d1=c(3,2), d2=c(4,8), d3=c(8,16))
x

x %>%
  rowwise() %>%
  mutate(agg=sum(f1*d1, f2*d2, f3*d3) / sum(f1, f2, f3) )

#Source: local data frame [2 x 7]
#Groups: <by row>

# A tibble: 2 x 7
#     f1    f2    f3    d1    d2    d3   agg
#  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#1  1.00  1.00  1.00  3.00  4.00  8.00  5.00
#2  1.00  0     1.00  2.00  8.00 16.0   9.00

但是,當有很多變量時,我失去了使用范圍的能力,所以我不能說“ f1 * d1”:“ f2 * d2”-還有一些更通用的方法嗎?

假設f列和d列具有相同的后綴並且長度相等,即f列和d列的數目相同,則可以使用select輔助函數:

x %>% 
    select(sort(names(x))) %>%   # sort the names so the f columns and d columns correspond
    mutate(agg = {
        fs = select(., starts_with('f')) 
        ds = select(., starts_with('d'))
        rowSums(fs * ds) / rowSums(fs) 
    })

#  d1 d2 d3 f1 f2 f3 agg
#1  3  4  8  1  1  1   5
#2  2  8 16  1  0  1   9

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM