首页 > 解决方案 > 一种读取数据表的方法

问题描述

我正在寻找一种方法,可以将这些文本行读入 df 列中,以便我可以在上面练习。

some text sample 1
some text sample  2 3
some more text 's sample here and then
another one
How to add text to df using read.table

输出:

                                   text
1                     some text sample 1
2                  some text sample  2 3
3    some more text 's sample here and then
4                            another one
5 How to add text to df using read.table

谢谢你帮助我。

标签: r

解决方案


我们可以使用readLines读取每一行然后转换为data.frame. 通过这种方式,我们可以确定它将读取一行作为一个整体,并且不依赖于任何分隔(如果存在)

data.frame(text = readLines('file.txt'))
#                                    text
#1                     some text sample 1
#2                  some text sample  2 3
#3 some more text 's sample here and then
#4                            another one
#5 How to add text to df using read.table

我们也可以使用read.table不同的sep

df <- read.table('file.txt', header = FALSE, col.names = 'txt', sep=",")

推荐阅读