R을 이용한 데이터처리 & 분석실무 책을 참고로 합니다. 정확한 지식은 책을 통해 얻으시길 바랍니다

보통 dataframe 안에 있는 data에 접근하기 위해서 dataframe$column.name 을 사용하는데 번거로울 수 있습니다.

많은 교재에서 attach(), detach()를 사용하는데 이를 남용하면 오히려 코드가 꼬여 나중에 검토가 어려워집니다.

그래서 가급적 DF$name을 많이 씁니다만 with(), within() 함수를 사용하는 방법도 있습니다.

1. with()

with() 함수는 dataframe 또는 list 내 field 이름만으로 field에 접근이 가능하게 해줍니다.

mean(iris$Sepal.Length)
## [1] 5.843333

이는 다음과 같이 표현할 수 있습니다.

with(iris, {
  mean(Sepal.Length)
})
## [1] 5.843333

{} 안에 묶이는 column이 많아지면 with를 사용하는게 편합니다.

2. within()

within() 함수는 with()와 동일하나 데이터를 수정할 수 있는 특징이 있습니다.

x <- data.frame(val = c(1, 2, 3, 4, NA, 5, NA))
x
##   val
## 1   1
## 2   2
## 3   3
## 4   4
## 5  NA
## 6   5
## 7  NA

x의 결측치를 없애봅시다.

x$val[is.na(x$val)] <- median(x$val, na.rm = T)
x
##   val
## 1   1
## 2   2
## 3   3
## 4   4
## 5   3
## 6   5
## 7   3

이를 within() 함수를 통해 할 수 있습니다.

x <- data.frame(val = c(1, 2, 3, 4, NA, 5, NA))
x <- within(x, {
  val <- ifelse(is.na(val), median(x$val, na.rm = T), val)
})
x
##   val
## 1   1
## 2   2
## 3   3
## 4   4
## 5   3
## 6   5
## 7   3

within() 함수를 실제 data에 활용하는 예시를 봅시다.

head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
iris[1, 1] = NA
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1           NA         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
median.per.species <- sapply(split(iris$Sepal.Length, iris$Species), median, na.rm= T)
median.per.species
##     setosa versicolor  virginica 
##        5.0        5.9        6.5
iris <- within(iris, {
  Sepal.Length <- ifelse(is.na(Sepal.Length), median.per.species[Species], Sepal.Length)
})

head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.0         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa

NA를 해당 species의 중앙값으로 치환할 수 있습니다.