用于操作 data.frames 的便捷功能
操作 data.frames 的一些便利功能是 subset(),transform(),with() 和 within()。
子集
subset() 函数允许你以更方便的方式对 data.frame 进行子集化(子集也可以与其他类一起使用):
subset(mtcars, subset = cyl == 6, select = c("mpg", "hp"))
mpg hp
Mazda RX4 21.0 110
Mazda RX4 Wag 21.0 110
Hornet 4 Drive 21.4 110
Valiant 18.1 105
Merc 280 19.2 123
Merc 280C 17.8 123
Ferrari Dino 19.7 175
在上面的代码中,我们只询问 cyl == 6 和列 mpg 和 hp 的行。你可以使用 [] 使用以下代码获得相同的结果:
mtcars[mtcars$cyl == 6, c("mpg", "hp")]
转变
transform() 函数是一个方便的函数,用于更改 data.frame 中的列。例如,下面的代码将另一个名为 mpg2 的列添加到 mpg^2 到 mtcars data.frame:
mtcars <- transform(mtcars, mpg2 = mpg^2)
与…内
with() 和 within() 都可以让你评估 data.frame 环境中的表达式,允许更清晰的语法,节省你使用一些 $ 或 []。
例如,如果要在 airquality data.frame 中创建,更改和/或删除多个列:
aq <- within(airquality, {
lOzone <- log(Ozone) # creates new column
Month <- factor(month.abb[Month]) # changes Month Column
cTemp <- round((Temp - 32) * 5/9, 1) # creates new column
S.cT <- Solar.R / cTemp # creates new column
rm(Day, Temp) # removes columns
})