将文本文件读入R [英] Read a Text File into R

查看:144
本文介绍了将文本文件读入R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,以前是否有人问过这个问题,但是我无法在网上或其他地方找到示例.

I apologize if this has been asked previously, but I haven't been able to find an example online or elsewhere.

我的文本文件中有非常脏的数据文件(可能是JSON).我想分析R中的数据,由于我还是该语言的新手,所以我想读取原始数据并根据需要进行操作.

I have very dirty data file in a text file (it may be JSON). I want to analyze the data in R, and since I am still new to the language, I want to read in the raw data and manipulate as needed from there.

如何从机器上的文本文件中读取JSON?另外,如果不是JSON,我如何按原样读取原始数据(不解析为列等),这样我就可以弄清楚如何根据需要解析它了?

How would I go about reading in JSON from a text file on my machine? Additionally, if it isn't JSON, how can I read in the raw data as is (not parsed into columns, etc.) so I can go ahead and figure out how to parse it as needed?

提前谢谢!

推荐答案

假设您的文件采用JSON格式,则可以尝试使用 jsonlite 包或 RJSONIO rjson .这三个包允许您使用fromJSON函数.

Suppose your file is in JSON format, you may try the packages jsonlite ou RJSONIO or rjson. These three package allows you to use the function fromJSON.

要安装软件包,请使用 install.packages 功能.例如:

To install a package you use the install.packages function. For example:

install.packages("jsonlite")

而且,只要安装了软件包,就可以使用功能库进行加载.

And, whenever the package is installed, you can load using the function library.

library(jsonlite) 

通常,以行分隔的JSON每行有一个对象.因此,您需要逐行阅读并收集对象.例如:

Generally, the line-delimited JSON has one object per line. So, you need to read line by line and collecting the objects. For example:

con <- file('myBigJsonFile.json') 
open(con)
objects <- list()
index <- 1
while (length(line <- readLines(con, n = 1, warn = FALSE)) > 0) {
    objects[[index]] <- fromJSON(line)
    index <- index + 1
} 
close(con)

在那之后,您将所有数据保存在 objects 变量中.使用该变量,您可以提取所需的信息.

After that, you have all the data in the objects variable. With that variable you may extract the information you want.

这篇关于将文本文件读入R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆