码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-11-05 16:40:21      阅读:393      评论:0      收藏:0      [点我收藏+]

标签:library   excel   资料   

              找整理了下资料,你看看,希望对你有帮助

             你下载一本资料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

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

标签:library   excel   资料   

原文地址:http://alicedai.blog.51cto.com/5589624/1710015

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!