R - 如何将文本文件读入列表? [英] R - How to read text file into a list?

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

问题描述

我有以下数据框 dat 和一个列表 b:

I have the following data frame dat and a list b:

Word = c("FOO", "BAM", "ZIP")
Count = c(7, 6, 2)
dat = data.frame(Word, Count)

b<-c("FOO")

我正在 dat 中创建第三列,像这样打印 TRUE 或 FALSE:

I'm creating a third column in dat that prints TRUE or FALSE like so:

dat<-data.frame(dat$Word,dat$Count, dat$Word %in% b)
colnames(dat)<-c("Word","Count","Condition")

打印:

>dat
Word    Count    Condition
FOO      7       TRUE
BAM      6       FALSE
ZIP      2       FALSE

到目前为止一切顺利.现在不是手动创建 b,我想将换行符分隔的文件读入 R,并且仍然能够使用我上面写的代码来创建 3 列数据框 dat.

So far so good. Now instead of creating b manually, I want to read in a newline-separated file into R, and still be able to use the code I wrote above to create the 3 column data frame dat.

我的意思是:

df1 <- read.table(text="FOO\nCAT\nDOG\nFISH\n")
dat<-data.frame(dat$Word,dat$Count, dat$Word %in% df1)
colnames(dat)<-c("Word","Count","Condition")

然而,这会打印:

>dat
Word    Count    Condition
FOO      7       FALSE
BAM      6       FALSE
ZIP      2       FALSE

而不是以前的工作方式.我的问题:如何将 words.txt 文件导入 df1 以便我上面编写的代码仍然有效?

Instead of how it worked before. My question: How do I import a file say words.txt into df1 so that the code I wrote above still works?

推荐答案

'df1' 返回一个 data.frame 列 'V1' 作为默认命名,因此我们需要提取该列即

The 'df1' returns a data.frame with column 'V1' as the default naming, So we need to extract that column i.e.

data.frame(Word = dat$Word,Count=dat$Count, Condition= dat$Word %in% df1[[1]])
#  Word Count Condition
#1  FOO     7      TRUE
#2  BAM     6     FALSE
#3  ZIP     2     FALSE

<小时>

如果我们需要这个作为vector,我们可以直接用scan

v1 <- scan(text="FOO\nCAT\nDOG\nFISH\n", what="", quiet=TRUE)
transform(dat, Condition = Word %in% v1) 
#   Word Count Condition
#1  FOO     7      TRUE
#2  BAM     6     FALSE
#3  ZIP     2     FALSE

注意:listvector 不同.在 list 中,元素可以是不同的类型,但在 vector 中,所有元素都是相同的 type.根据所需的输出,vector 似乎是我们在这里的目标.

NOTE: A list is different from a vector. In a list, the elements can be of different types, but in a vector all of them are of the same type. Based on the output required, it seems that vector is what we are aiming for here.

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

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