with(data, expr, …)
该函数表示,利用data数据框中的数据,进行expr中代码的运算
实例
a='out'
df=data.frame(x=c(1,2,3),y=c(5,6,8))
with(df,
{a=x+y
b=x-y
print(a)
}
)
# [1] 6 8 11
a
# [1] "out"
注意,expr中的变量是局部变量。
by(data, INDICES, FUN, …, simplify = TRUE)
该函数表示根据indices的分类对data中的数据使用fun进行处理。data可以是一个数据框,矩阵或者list.
实例
df=data.frame(x=c(1,2,3,5,6),y=c(1,2,5,6,8),id=c('a','a','b','b','c'))
by(df,df$id,summary)
# df$id: a
# x y id
# Min. :1.00 Min. :1.00 Length:2
# 1st Qu.:1.25 1st Qu.:1.25 Class :character
# Median :1.50 Median :1.50 Mode :character
# Mean :1.50 Mean :1.50
# 3rd Qu.:1.75 3rd Qu.:1.75
# Max. :2.00 Max. :2.00
# ---------------------------------------------------------
# df$id: b
# x y id
# Min. :3.0 Min. :5.00 Length:2
# 1st Qu.:3.5 1st Qu.:5.25 Class :character
# Median :4.0 Median :5.50 Mode :character
# Mean :4.0 Mean :5.50
# 3rd Qu.:4.5 3rd Qu.:5.75
# Max. :5.0 Max. :6.00
# ---------------------------------------------------------
# df$id: c
# x y id
# Min. :6 Min. :8 Length:1
# 1st Qu.:6 1st Qu.:8 Class :character
# Median :6 Median :8 Mode :character
# Mean :6 Mean :8
# 3rd Qu.:6 3rd Qu.:8
# Max. :6 Max. :8
df=data.frame(id=c('a','b','c','c'),x=c(1,5,4,7))
Mean=by(df$x,df$id,mean)
Med=by(df$x,df$id,median)
df2=rbind(Mean,Med)
df2
# a b c
# Mean 1 5 5.5
# Med 1 5 5.5