dplyr을 사용하여 R에서 여러 변수를 업데이트하기 위해 단일 조건문을 사용하려고합니다. 작업 코드 (아래에 게시 됨)가 있지만 매우 비효율적이며 더 나은 방법이 있어야한다고 확신합니다.
편집 : 프로그램의 목적에 대한 설명. 아이디어는 홍채 데이터 세트를 사용하여 Species 값을 기반으로 여러 변수를 업데이트하는 것입니다. 예를 들어 Species == "setosa"then Species = "SETOSA", Sepal.Length * = 1.5, Sepal.Width * = 0.5입니다.
library(dplyr)
library(tibble)
multi_update <- function(species , sepal.length , sepal.width , ret){
if ( species == "setosa") {
RET <- list(
Species = "SETOSA",
Sepal.Length = sepal.length * 1.5,
Sepal.Width = sepal.width * 0.5
)
} else if ( species == "versicolor") {
RET <- list(
Species = "VERSI",
Sepal.Length = sepal.length * 2,
Sepal.Width = sepal.width * 1.5
)
} else {
RET <- list(
Species = species,
Sepal.Length = sepal.length ,
Sepal.Width = sepal.width
)
}
return( RET[[ret]] )
}
iris %>%
tbl_df %>%
mutate( Sepal.Length = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Sepal.Length")) %>%
mutate( Sepal.Width = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Sepal.Width")) %>%
mutate( Species = mapply(multi_update , Species , Sepal.Length , Sepal.Width , "Species"))
join
원래 데이터 세트와 mutate
열을 사용하여 key val 데이터 세트를 만들 수 있습니다.
library(dplyr)
kval <- data.frame(Species = c("setosa", "versicolor", "virginica"),
Species.x = c("SETOSA", "VERSI", "virginica"),
Sepal.Length = c(1.5, 2, 1), Sepal.Width = c(0.5, 1.5, 1))
res <- left_join(iris, kval, by = "Species") %>%
mutate(Species = Species.x, Sepal.Length = Sepal.Length.x*Sepal.Length.y,
Sepal.Width = Sepal.Width.x * Sepal.Width.y) %>%
select(-matches("(.x|.y)$"))
head(res)
# Petal.Length Petal.Width Species Sepal.Length Sepal.Width
#1 1.4 0.2 SETOSA 7.65 1.75
#2 1.4 0.2 SETOSA 7.35 1.50
#3 1.3 0.2 SETOSA 7.05 1.60
#4 1.5 0.2 SETOSA 6.90 1.55
#5 1.4 0.2 SETOSA 7.50 1.80
#6 1.7 0.4 SETOSA 8.10 1.95
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다