在 R 编程中使用表达式修改数据帧的数据 - with()函数
R 语言中的with()
函数用于通过计算函数参数中的表达式来修改数据帧的数据。
Syntax: with(x, expr)
Parameters:
x: Data frame
expr: Expression to modify data
示例 1:
# R program to modify data of an object
# Calling predefined data set
BOD
# Calling with() function
with(BOD, {BOD$demand <- BOD$demand + 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, {df$Age <- df$Age + 10; print(df$Age)})
输出:
Name Language Age
1 abc R 22
2 def Python 25
3 ghi Java 45
[1] 32 35 55