R语言 用表达式修改数据框的数据 – with()函数
R语言中的 with() 函数用于通过评估函数参数中的表达式来修改数据框的数据。
语法: with(x, expr)
参数:
x: 数据框
expr: 修改数据的表达式
例子1 :
# R program to modify data of an object
# Calling predefined data set
BOD
# Calling with() function
with(BOD, {BODdemand <- BODdemand + 1; print(BOD$demand)})
输出
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
[1] 9.3 11.3 20.0 17.0 16.6 20.8
例2 :
# R program to modify data of an object
# Creating a data frame
df = data.frame(
"Name" = c("abc", "def", "ghi"),
"Language" = c("R", "Python", "Java"),
"Age" = c(22, 25, 45)
)
df
# Calling with() function
with(df, {dfAge <- dfAge + 10; print(df$Age)})
输出
Name Language Age
1 abc R 22
2 def Python 25
3 ghi Java 45
[1] 32 35 55