假设我有一个凌乱的文本文件,例如以下
Today is a good
day, but I feel very tired. It seems like it is
going to rain pretty soon.
我想将txt文件作为字符向量读入R中,就像在原始文本文件中一样。换句话说,我希望字符向量的第一个元素是第一行,字符向量的第二个元素是第二行,如下所示
char_vector[1] = "Today is a good"
char_vector[2] = "day, but I feel very tired. It seems like it is"
char_vector[3] = "going to rain pretty soon."
我已经尝试过read.table和read.csv,但总是有些行连接在一起作为一行。有办法解决这个问题吗?
答案 0 :(得分:4)
char_vector <- readLines(filename)
txt <- "Today is a good
day, but I feel very tired. It seems like it is
going to rain pretty soon."
readLines(textConnection(txt) )
# ---- teh screen output of three distinct character elements
[1] "Today is a good"
[2] "day, but I feel very tired. It seems like it is"
[3] "going to rain pretty soon."
char_vector <- readLines(textConnection(txt))
char_vector[1]
#[1] "Today is a good"
答案 1 :(得分:1)
扫描可以做到这一点。
scan( file="myfile.txt", what=character() )
答案 2 :(得分:0)
您可以使用readLines
功能。