> df1<-head(mtcars)
> df1<-df1[1:3]
> df1
mpg cyl disp
Mazda RX4 21.0 6 160
Mazda RX4 Wag 21.0 6 160
Datsun 710 22.8 4 108
Hornet 4 Drive 21.4 6 258
Hornet Sportabout 18.7 8 360
Valiant 18.1 6 225
> df1$cyl
[1] 6 6 4 6 8 6
> df1$mpg
[1] 21.0 21.0 22.8 21.4 18.7 18.1
> attach(df1)#绑定df1数据框
> mpg
[1] 21.0 21.0 22.8 21.4 18.7 18.1
> cyl
[1] 6 6 4 6 8 6
> mpg+cyl+disp
[1] 187.0 187.0 134.8 285.4 386.7 249.1
> detach(df1)#解除绑定df1数据框
> mpg
Error: object 'mpg' not found
> df1$mpg+df1$cyl+df1$disp
[1] 187.0 187.0 134.8 285.4 386.7 249.1
> with(df1,{mpg+cyl+disp})#简化数据框操作
[1] 187.0 187.0 134.8 285.4 386.7 249.1
> df1<-within(df1,{
+ sum=mpg+cyl+disp
+ mean=(mpg+cyl+disp)/3
+ }) #增加两列
> df1
mpg cyl disp mean sum
Mazda RX4 21.0 6 160 62.33333 187.0
Mazda RX4 Wag 21.0 6 160 62.33333 187.0
Datsun 710 22.8 4 108 44.93333 134.8
Hornet 4 Drive 21.4 6 258 95.13333 285.4
Hornet Sportabout 18.7 8 360 128.90000 386.7
Valiant 18.1 6 225 83.03333 249.1
> df1<-head(mtcars)
> df1<-df1[1:3]
> df1
mpg cyl disp
Mazda RX4 21.0 6 160
Mazda RX4 Wag 21.0 6 160
Datsun 710 22.8 4 108
Hornet 4 Drive 21.4 6 258
Hornet Sportabout 18.7 8 360
Valiant 18.1 6 225
> df1<-transform(df1,s=mpg+cyl+disp,m=(mpg+cyl+disp)/3)#变形增加两列
> df1
mpg cyl disp s m
Mazda RX4 21.0 6 160 187.0 62.33333
Mazda RX4 Wag 21.0 6 160 187.0 62.33333
Datsun 710 22.8 4 108 134.8 44.93333
Hornet 4 Drive 21.4 6 258 285.4 95.13333
Hornet Sportabout 18.7 8 360 386.7 128.90000
Valiant 18.1 6 225 249.1 83.03333
> df1<-head(mtcars)
> df1<-df1[1:3]
> library(dplyr)#dplyr是数据处理包
载入程辑包:‘dplyr’
The following objects are masked from ‘package:stats’:
filter, lag
The following objects are masked from ‘package:base’:
intersect, setdiff, setequal, union
> mutate(df1,s=mpg+cyl+disp,m=(mpg+cyl+disp)/3)
mpg cyl disp s m
1 21.0 6 160 187.0 62.33333
2 21.0 6 160 187.0 62.33333
3 22.8 4 108 134.8 44.93333
4 21.4 6 258 285.4 95.13333
5 18.7 8 360 386.7 128.90000
6 18.1 6 225 249.1 83.03333
> df1<-mutate(df1,s=mpg+cyl+disp,m=(mpg+cyl+disp)/3)
> df1#"mutate"与"transform"的区别在于”mutate"能直接对函数中前面的数值进行定义,而"transform"不能,比如:
mpg cyl disp s m
1 21.0 6 160 187.0 62.33333
2 21.0 6 160 187.0 62.33333
3 22.8 4 108 134.8 44.93333
4 21.4 6 258 285.4 95.13333
5 18.7 8 360 386.7 128.90000
6 18.1 6 225 249.1 83.03333
> df1<-mutate(df1,s=mpg+cyl+disp,m=(mpg+cyl+disp)/3,x=s+m)#"mutate"与"transform"的区别在于”mutate"能直接对函数中前面的数值进行定义,
> #而"transform"不能
> df1
mpg cyl disp s m x
1 21.0 6 160 187.0 62.33333 249.3333
2 21.0 6 160 187.0 62.33333 249.3333
3 22.8 4 108 134.8 44.93333 179.7333
4 21.4 6 258 285.4 95.13333 380.5333
5 18.7 8 360 386.7 128.90000 515.6000
6 18.1 6 225 249.1 83.03333 332.1333
> df1<-head(mtcars)
> df1<-df1[1:3]
> transform(df1,s=mpg+cyl+disp,m=(mpg+cyl+disp)/3,x=s+m)#此函数错误
Error in eval(substitute(list(...)), `_data`, parent.frame()) :
object 's' not found