2016-07-19 1 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 같이) dataframe를 사용하는 방법은 없나요? 분자가 분모 전 (폭 전에 즉. 길이) 항상 있다고 가정

# 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

관련 문제