2016-07-19 10 views
1

文字列変数から列を選択し、いくつかの計算を実行しようとしています。
dplyrを使用した文字列変数からの列選択

私はirisを分析していて、長さと幅の比率をすべて調べたいとします。

# Manual mutation (ie: adding the column names explicitly in the mutate statement) 
iris %>% 
    mutate(Sepal.ratio = Sepal.Length/Sepal.Width, 
     Petal.ratio = Petal.Length/Petal.Width) 

# Output: 
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.ratio Petal.ratio 
# 1   5.1   3.5   1.4   0.2 setosa 1.457143  7.00 
# 2   4.9   3.0   1.4   0.2 setosa 1.633333  7.00 
# 3   4.7   3.2   1.3   0.2 setosa 1.468750  6.50 
# 4   4.6   3.1   1.5   0.2 setosa 1.483871  7.50 
# 5   5.0   3.6   1.4   0.2 setosa 1.388889  7.00 
# 6   5.4   3.9   1.7   0.4 setosa 1.384615  4.25 


質問: は、列名を指定する変数または(以下に定義ratioSetsのような)データフレームを使用する方法はありますか?

# Predefined or preprocessed column name set: 
ratioSets = rbind(c(value = 'Sepal.ratio', numerator = 'Sepal.Length', denominator = 'Sepal.Width'), 
       c(value = 'Petal.ratio', numerator = 'Petal.Length', denominator = 'Petal.Width')) 

# Automated mutation: 
iris %>% 
    mutate(
    # How can I use the ratioSets here? 
    # Something like : ratioSets$value = ratioSets$numerator/ratioSets$denominator 
) 


# Expected Output: 
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.ratio Petal.ratio 
# 1   5.1   3.5   1.4   0.2 setosa 1.457143  7.00 
# 2   4.9   3.0   1.4   0.2 setosa 1.633333  7.00 
# 3   4.7   3.2   1.3   0.2 setosa 1.468750  6.50 
# 4   4.6   3.1   1.5   0.2 setosa 1.483871  7.50 
# 5   5.0   3.6   1.4   0.2 setosa 1.388889  7.00 
# 6   5.4   3.9   1.7   0.4 setosa 1.384615  4.25 
+0

私はあなたが望むものを理解していません。あなたは、あなたの意図した出力のいくつかの行を含めることができますか? – Maiasaura

+0

@Maiasaura私は質問にさらに説明を加えました。まだ明らかでない場合は教えてください。 – Deena

+0

今、完璧です。これは 'dplyr'でやや難しいですが、私はそれを考えています。 – Maiasaura

答えて

1

分子が分母の前に常にあることを前提として一つの方法(すなわち。幅前の長さ)

sapply(unique(sub('\\..*', '', names(iris[,-ncol(iris)]))), function(i) 
     Reduce('/', iris[,-ncol(iris)][,grepl(i, sub('\\..*', '', names(iris[,-ncol(iris)])))])) 

または

head(cbind(iris, sapply(unique(sub('\\..*', '', names(iris[,-ncol(iris)]))), 
     function(i) Reduce('/', iris[,-ncol(iris)][,grepl(i, sub('\\..*', '', names(iris[,-ncol(iris)])))])))) 

# Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal Petal 
#1   5.1   3.5   1.4   0.2 setosa 1.457143 7.00 
#2   4.9   3.0   1.4   0.2 setosa 1.633333 7.00 
#3   4.7   3.2   1.3   0.2 setosa 1.468750 6.50 
#4   4.6   3.1   1.5   0.2 setosa 1.483871 7.50 
#5   5.0   3.6   1.4   0.2 setosa 1.388889 7.00 
#6   5.4   3.9   1.7   0.4 setosa 1.384615 4.25 
+0

@Sotosありがとうございます。 'dplyr'の' mutate'を介してそれを置く方法があるかどうか知っていますか? – Deena

+0

確かにあります。私のコードを 'dplyr'に翻訳するとよいでしょう:) – Sotos

+0

実際に、私が直面している主な課題は、変数名をdplyrに渡すことです。この例では、dplyrで正しくインデックスできない値を事前に設定しています。 – Deena

関連する問題