日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

R语言数据接口(下载、读取、写入)

發布時間:2023/12/10 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 R语言数据接口(下载、读取、写入) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • R_數據接口
    • ref
      • csv文件
      • Excel文件
      • 二進制文件
      • xml文件
      • json文件
      • web數據
      • 數據庫

R_數據接口

ref

w3school_R_數據接口

csv文件

讀寫csv

  • 獲取和設置工作目錄

    • **getwd()**函數檢查R語言工作區指向的目錄。
    • **setwd()**函數設置新的工作目錄。
  • 讀取csv文件:read.csv(),將輸出作為數據幀

    • data <- read.csv("input.csv") print(data)# resultid, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance
  • 分析csv文件

    • 行列數

      print(ncol(data)) print(nrow(data))
    • 某列最大值

      sal <- max(data$salary) print(sal)
    • 特定條件篩選,類似SQL語句

      subset(data, condition)

      # Get the person detail having max salary. retval <- subset(data, salary == max(salary)) print(retval) # Create a data frame. data <- read.csv("input.csv")retval <- subset( data, dept == "IT") print(retval)
  • 寫入csv文件

    • **write.csv()**函數用于創建csv文件,并寫入數據幀。 此文件在工作目錄中創建。

      data <- read.csv("input.csv") retval <- subset(data, as.Date(start_date) > as.Date("2014-01-01"))# Write filtered data into a new file. write.csv(retval,"output.csv")
    • 默認寫入行名,可以write.csv(retval,"output.csv", row.names = FALSE)去除

Excel文件

  • 安裝、導入xlsl包

    • install.packages("xlsx")# Verify the package is installed. any(grepl("xlsx",installed.packages()))# Load the library into R workspace. library("xlsx")
  • 讀入xlsl文件

    • # sheetIndex = 1表示讀取第一個sheet data <- read.xlsx("input.xlsx", sheetIndex = 1) print(data)
  • 寫入xlsl文件

二進制文件

R語言有兩個函數WriteBin()和readBin()來創建和讀取二進制文件。

  • 語法

    writeBin(object, con) readBin(con, what, n )
    • con 是讀取或寫入二進制文件的連接對象。
    • object 是要寫入的二進制文件。
    • what - 是像字符,整數等代表字節模式被讀取。
    • n 是從二進制文件讀取的字節數。

xml文件

  • 安裝xml包

    install.packages("XML")
  • 讀取xml

    • 使用函數**xmlParse()**讀取。 它作為列表存儲在R語言中。

      # Load the package required to read XML files. library("XML")# Also load the other required package. library("methods")# Give the input file name to the function. result <- xmlParse(file = "input.xml")# Print the result. print(result)
    • 獲取根節點(是個列表)和文件節點數

      # Exract the root node form the xml file. rootnode <- xmlRoot(result)# Find number of nodes in the root. rootsize <- xmlSize(rootnode)
    • 解析文件第一條記錄

      print(rootnode[1])
    • 獲取節點的不同元素

      # Get the second element of the third node. print(rootnode[[3]][[2]])
    • xml轉數據幀

      xmldataframe <- xmlToDataFrame("input.xml") print(xmldataframe)
  • 寫入xml

json文件

  • 安裝rjson包

    install.packages("rjson")
  • 讀取json文件

    # Load the package required to read JSON files. library("rjson")# Give the input file name to the function. result <- fromJSON(file = "input.json")# Print the result. print(result)
  • json轉數據幀

    • 使用**as.data.frame()**函數將上面提取的數據轉換為R語言數據幀以進行進一步分析

      # Load the package required to read JSON files. library("rjson")# Give the input file name to the function. result <- fromJSON(file = "input.json")# Convert JSON file to a data frame. json_data_frame <- as.data.frame(result)print(json_data_frame)
  • 寫入json文件

web數據

許多網站提供數據供其用戶使用。

使用R語言程序,我們可以從這些網站以編程方式提取特定數據。

R語言中用于從網站中提取數據的一些包是“RCurl”,XML“和”stringr“,它們用于連接到URL,識別文件所需的鏈接并將它們下載到本地環境。

  • 安裝包

    install.packages("RCurl") install.packages("XML") install.packages("stringr") install.packages("plyr")
  • demo[主要是獲取link,再逐個下載]

    • 使用函數getHTMLLinks()來收集文件的URL
    • 使用函數downlaod.file()將文件保存到本地系統
    # Read the URL. url <- "http://www.geos.ed.ac.uk/~weather/jcmb_ws/"# Gather the html links present in the webpage. links <- getHTMLLinks(url)# Identify only the links which point to the JCMB 2015 files. filenames <- links[str_detect(links, "JCMB_2015")]# Store the file names as a list. filenames_list <- as.list(filenames)# Create a function to download the files by passing the URL and filename list. downloadcsv <- function (mainurl,filename) {filedetails <- str_c(mainurl,filename)download.file(filedetails,filename) }# Now apply the l_ply function and save the files into the current R working directory. l_ply(filenames,downloadcsv,mainurl = "http://www.geos.ed.ac.uk/~weather/jcmb_ws/")

數據庫

數據是關系數據庫系統以規范化格式存儲。

  • 安裝包

    install.packages("RMySQL")
  • 連接mysql

    • R中創建一個連接對象以連接到數據庫。 它使用用戶名,密碼,數據庫名稱和主機名作為輸入。

    • 使用dbConnect()函數創建連接對象

      mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', host = 'localhost')
    # Create a connection Object to MySQL database. # We will connect to the sampel database named "sakila" that comes with MySql installation. mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', host = 'localhost')# List the tables available in this database.dbListTables(mysqlconnection)
  • 查詢

    • 使用函數dbSendQuery()查詢MySql中的數據庫表。

      result = dbSendQuery(mysqlconnection,SQL)
    • 使用R語言fetch()函數返回結果集

      data.frame = fetch(result, n = rows_display) # -1表示所有
    • 最后,它被存儲為R語言中的數據幀。

    # Query the "actor" tables to get all the rows. result = dbSendQuery(mysqlconnection, "select * from actor")# Store the result in a R data frame object. n = 5 is used to fetch first 5 rows. data.frame = fetch(result, n = 5) print(data.frame)
  • 更新

    • 將更新查詢傳遞給**dbSendQuery()**函數來更新Mysql表中的行。

      dbSendQuery(mysqlconnection, "update mtcars set disp = 168.5 where hp = 110")
  • 插入

    dbSendQuery(mysqlconnection,"insert into mtcars(row_names, mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb)values('New Mazda RX4 Wag', 21, 6, 168.5, 110, 3.9, 2.875, 17.02, 0, 1, 4, 4)" )
  • 建表

    • 使用函數dbWriteTable()創建表。 如果表已經存在,它將覆蓋該表,并將數據幀用作輸入。

      # Create the connection object to the database where we want to create the table. mysqlconnection = dbConnect(MySQL(), user = 'root', password = '', dbname = 'sakila', host = 'localhost')# Use the R data frame "mtcars" to create the table in MySql. # All the rows of mtcars are taken inot MySql. dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)
  • 刪除表

    dbSendQuery(mysqlconnection, 'drop table if exists mtcars')

總結

以上是生活随笔為你收集整理的R语言数据接口(下载、读取、写入)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。