在 R 编程中评估表达式 - with() 和 within()函数
R 编程中的with()
函数在由数据本地构建的环境中计算表达式,并且不会创建数据的副本。
Syntax: with(data, expr)
Parameters:
data represents dataset to be used
expr represents formula or expression to be evaluated
示例 1:
# Creating list
df <- list("x1" = c(1, 2, 3),
"x2" = c(4, 5, 6),
"x3" = c(7, 8, 9))
with(df, x1 + x2 + x3)
输出:
[1] 12 15 18
示例 2:
# Using mtcars dataset
with(mtcars, mean(mpg + cyl + disp))
输出:
[1] 257
内()函数
R 编程中的 inside within()
函数在本地创建的环境中评估表达式并修改数据的副本,这与with()
函数不同。
Syntax: within(data, expr)
Parameters:
data represents dataset to be used
expr represents formula or expression to be evaluated
示例 1:
# Creating a data frame
df <- list("x1" = c(1, 2, 3),
"x2" = c(4, 5, 6))
within(df, x3 <- x1 + x2)
输出:
$x1
[1] 1 2 3
$x2
[1] 4 5 6
$x3
[1] 5 7 9
示例 2:
# Using airquality dataset
aq <- within(airquality, {
newOzone <- log(Ozone)
cTemp <- round((Temp - 32) * 5/9, 1) # Fahrenheit to Celsius
})
head(aq)
输出:
Ozone Solar.R Wind Temp Month Day cTemp newOzone
1 41 190 7.4 67 5 1 19.4 3.713572
2 36 118 8.0 72 5 2 22.2 3.583519
3 12 149 12.6 74 5 3 23.3 2.484907
4 18 313 11.5 62 5 4 16.7 2.890372
5 NA NA 14.3 56 5 5 13.3 NA
6 28 NA 14.9 66 5 6 18.9 3.332205