R语言笔记——运行SQL查询
本个专题将介绍R语言的一些基本技能和实用技巧。本教程说明了如何在带有sqldf包的R中运行sql查询。
01
安装并加载软件包
install.packages("sqldf")
library(sqldf)
02
创建样本数据
'X1','X2','X4','X2','X1','X4','X3','X2','X1','X3'), dt <- data.frame( ID = c(
+ Value = c(4,3,1,3,4,6,6,1,8,4))
# ID Value
# 1 X1 4
# 2 X2 3
# 3 X4 1
# 4 X2 3
# 5 X1 4
# 6 X4 6
# 7 X3 6
# 8 X2 1
# 9 X1 8
# 10 X3 4
示例1:选择前3行
"select * from dt limit 3") x = sqldf(
# ID Value
# 1 X1 4
# 2 X2 3
# 3 X4 1
示例2:处理列和表名称中的点
将名称放在双引号中
test <- data.frame( x.1 = 1:10 )
'SELECT "x.1" FROM test' ) sqldf(
# x.1
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
# 6 6
# 7 7
# 8 8
# 9 9
# 10 10
> test.2 = data.frame(x= sample(10))
> sqldf( 'SELECT * FROM "test.2" ' )
# x
# 1 6
# 2 3
# 3 1
# 4 9
# 5 8
# 6 4
# 7 7
# 8 2
# 9 10
# 10 5
示例3:子集
"select * from dt where Value >= 4") x2 = sqldf(
# ID Value
# 1 X1 4
# 2 X1 4
# 3 X4 6
# 4 X3 6
# 5 X1 8
# 6 X3 4
示例4:连接两个数据帧
"select * from x union all select * from x2") x3 = sqldf(
# ID Value
# 1 X1 4
# 2 X2 3
# 3 X4 1
# 4 X1 4
# 5 X1 4
# 6 X4 6
# 7 X3 6
# 8 X1 8
# 9 X3 4
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆
◆