문자열 변수에서 열을 선택하고 일부 계산을 수행하려고합니다.
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
내가 당신이 원하는 것을 이해하지 않습니다. 몇 줄의 출력물을 포함시킬 수 있습니까? – Maiasaura
@Maiasaura 질문에 대한 추가 설명을 추가했습니다. 아직 명확하지 않은 경우 알려 주시기 바랍니다. – Deena
완벽하고, 지금은 의미가 있습니다. 이것은'dplyr'에서 조금 도전적이지만 나는 그것을 통해 생각하고 있습니다. – Maiasaura