2016-11-29 9 views
2

名前のパターンに基づいて合計する必要があるいくつかの変数を持つdata.frameがあります。より具体的には、私には、最大1つのシェアがあります。私はこれにdplyrを使用しています。dplyr突然変異体で特定のパターンを持つ変数を集計する

サンプルdata.frame:私はこのようなends_with機能を使用しようとしました

df <- data.frame(year = c(2000, 2001, 2002), 
      aShare = c(.1,.2,.3), 
      bShare = c(.3,.4,.5)) 

tmp <- df %>% mutate(otherShare = 1 - sum(ends_with("Share"))) 

しかし、それは必要な結果を生成しません:

TMP <- df %>% mutate(otherShare = 1 - (aShare + bShare)) 

答えて

5

をベース付きR

半dplyrで
df$x <-1- rowSums(df[colnames(df)[grepl("Share",colnames(df))]]) 

:P

df$x = (1-df %>% select(ends_with("Share")) %>% rowSums()) 
+3

別のバリエーションを使用することができます: 'DF%>%(otherShare =を変異を1 - select(。、ends_with( "Share"))%>%rowSums()) ' –

+1

これは非常に便利です。私はあなたから学んだ。 – aichao

1

ない、おそらく最良の選択肢が、我々はapply行単位

df$otherShare <- apply(df[grep("Share$", names(df))], 1, function(x) 1 - sum(x)) 

# year aShare bShare otherShare 
#1 2000 0.1 0.3  0.6 
#2 2001 0.2 0.4  0.4 
#3 2002 0.3 0.5  0.2 
関連する問題