在R脚本中导入数据

在R脚本中导入数据

在这篇文章中,我们将看到如何 用R编程语言导入数据

R语言 导入数据

首先,让我们考虑一个数据集,我们可以用来做示范。对于这个演示,我们将使用两个单一数据集的例子,一个是.csv形式,另一个是.txt形式。

在R脚本中导入数据

读取逗号分隔值(CSV)文件

方法1:使用read.csv()函数读取CSV文件到R中

该函数有两个参数

  • file.choice(): 它打开一个菜单,从桌面上选择一个csv文件。
  • header: 它是表示数据集的第一行是否是变量名。如果变量名存在,应用T/True,否则放F/False。

例子

# import and store the dataset in data1
data1 <- read.csv(file.choose(), header=T)
 
# display the data
data1

输出

在R脚本中导入数据

方法2:使用read.table()函数

这个函数指定了数据集的分离方式,在这种情况下,我们把 sep=”, “ 作为参数。

例子

# import and store the dataset in data2
data2 <- read.table(file.choose(), header=T, sep=", ")
 
# display data
data2

输出

在R脚本中导入数据

在R编程语言中读取带制表符的(txt)文件

方法1:使用read.delim()函数

该函数有两个参数。

  • file.select(): 它打开一个菜单,从桌面上选择一个csv文件。
  • header: 它是为了表明数据集的第一行是否是变量名。如果变量名存在,应用T/True,否则放F/False。

例子

# import and store the dataset in data3
data3 <- read.delim(file.choose(), header=T)
 
# display the data
data3

输出

在R脚本中导入数据

方法2:使用read.table()函数

这个函数指定了数据集的分离方式,在本例中我们采用 sep=” \t “作为参数。

例子

# import and store the dataset in data4
data4 <- read.table(file.choose(), header=T, sep="\t")
 
# display the data
data4

输出

在R脚本中导入数据

使用R-Studio

在这里,我们将通过R studio导入数据,步骤如下。

步骤

  • 从环境选项卡上点击导入数据集菜单
  • 从选项中选择文件扩展名
  • 在第三步,会出现一个弹出框,输入文件名或浏览桌面。
  • 选定的文件将显示在一个新的窗口上,并显示其尺寸。
  • 为了在控制台上看到输出,请输入文件名。

例子

# display the dataset
dataset

输出

在R脚本中导入数据

  • 为了将数据加载到控制台使用,我们使用 attach 命令。

例子

# To load the data for use
attach(dataset)

R语言 读取JSON文件

为了在R中处理JSON文件,人们需要安装 “rjson “包。在rjson包下使用JSON文件完成的最常见的任务如下。

  • 在R控制台安装并加载rjson包
  • 创建一个JSON文件
  • 从JSON文件中读取数据
  • 写入JSON文件
  • 将JSON数据转换为数据帧
  • 使用URL工作

用于演示的JSON文件

{ 
   "ID":["1","2","3","4","5"],
   "Name":["Mithuna","Tanushree","Parnasha","Arjun","Pankaj"],
   "Salary":["722.5","815.2","1611","2829","843.25"],
   "StartDate":["6/17/2014","1/1/2012","11/15/2014","9/23/2013","5/21/2013"],
   "Dept":["IT","IT","HR","Operations","Finance"]
}

代码

# Read a JSON file
 
# Load the package required to read JSON files.
library("rjson")
 
# Give the input file name to the function.
result <- fromJSON(file = "E:\\example.json")
 
# Print the result.
print(result)

输出

$ID
[1] "1" "2" "3" "4" "5"

$Name
[1] "Mithuna"   "Tanushree" "Parnasha"  "Arjun"     "Pankaj"

$Salary
[1] "722.5"  "815.2"  "1611"   "2829"   "843.25"

$StartDate
[1] "6/17/2014"  "1/1/2012"   "11/15/2014" "9/23/2013"  "5/21/2013"

$Dept
[1] "IT"         "IT"         "HR"         "Operations" "Finance"

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程