您的位置:首页 > 其它

R语言读取Excel和对数据框的操作

2015-11-05 14:50 543 查看
找整理了下资料,你看看,希望对你有帮助
你下载一本资料http://down.51cto.com/data/957270
导入Excel数据请参考书中的2.3.3, 使用SQL语句操作数据框请参考书中的4.11节
你可以根据自己的功能分写成不同的脚本,使用的时候直接使用就可以了

 我使用了以下方法:
install.packages("XLConnect") library("XLConnect") 这里有weatherday.xlsx, 我放在workspace下面, getwd()获取workspace, setwd("E:/")设置workspace  至此,已把所有数据读出,见下图


使用SQL语句操作数据框
install.packages("sqldf") 安装sqldf的库文件
library("sqldf") 加载sqldf库

newdf <- sqldf("select * from df where y = 1963 and d = 10 order by m",row.names=TRUE)将执行结果放到一个新的数据框newdf中
View(newdf) 查看newdf的内容

a <- sqldf("select avg(mt) as mt_avg, avg(p) as p_avg from df where y = 1963 and d <= 10 ", row.names=TRUE)
View(a)
总共的执行代码如下:
install.packages("XLConnect")
install.packages("sqldf")
library("XLConnect")
library("sqldf")
setwd("E:/")
df <- readWorksheetFromFile("weatherday.xlsx",sheet=1,header=TRUE)
newdf <- sqldf("select * from df where y = 1963 and d = 10 order by m",row.names=TRUE)
View(newdf)
a <- sqldf("select avg(mt) as mt_avg, avg(p) as p_avg from df where y = 1963 and d <= 10 ", row.names=TRUE)
View(a)
结果显示最后一次的View结果
最后一段代码中的 1963,10 你可以用变量代替,如下,每次改动year,day的值即可

install.packages("XLConnect")
install.packages("sqldf")
library("XLConnect")
library("sqldf")
year <- 1963
day <- 10
setwd("E:/")
df <- readWorksheetFromFile("weatherday.xlsx",sheet=1,header=TRUE)
newdf <- sqldf("select * from df where y = year and d = day order by m",row.names=TRUE)
View(newdf)
a <- sqldf("select avg(mt) as mt_avg, avg(p) as p_avg from df where y = year and d <= day ", row.names=TRUE)
View(a)

本文出自 “不会撒娇的猫” 博客,请务必保留此出处http://alicedai.blog.51cto.com/5589624/1710015
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: