简体   繁体   English

如何根据来自其他几个文件的值来创建R中的表1和0

[英]How to create a table in R with 1s and 0s based on the presence of values from several other files

I have five different text files that all contain 7 digit lines. 我有五个不同的文本文件,都包含7位数行。 I want to create a table that tells me, using 1s and 0s, whether the line is present in the file. 我想创建一个表,告诉我,使用1和0,该行是否存在于文件中。

For example: 例如:

        file1.txt  file2.txt  file3.txt
xxxxxxx     1         0           1
xxxxxxx     0         1           1
xxxxxxx     1         1           1

I have little to no experience in R, or any kind of coding. 我对R或任何编码都没什么经验。 Can someone help me? 有人能帮我吗? I can add more information if someone asks. 如果有人问,我可以添加更多信息。

Assuming three files exist: 假设存在三个文件:

==> file1.txt <==
1111111
3333333

==> file2.txt <==
2222222
3333333

==> file3.txt <==
1111111
2222222
3333333

I would read the three files into separate dataframes: 我会将这三个文件读入单独的数据帧:

file1=read.csv('file1.txt', header=FALSE)
file2=read.csv('file3.txt', header=FALSE)
file3=read.csv('file3.txt', header=FALSE)

Add a flag to each: 为每个添加一个标志:

file1$file1.txt <- rep(1,nrow(file1))
file2$file2.txt <- rep(1,nrow(file2))
file3$file3.txt <- rep(1,nrow(file3))

Perform an outer join using merge , replace NA values with 0 and name rows with the values 使用merge执行外部merge ,将NA值替换为0,并使用值命名行

merged=merge(merge(file1,file2, all=TRUE), file3, all=TRUE)
merged[is.na(merged)] <- 0
rownames(merged) <- merged[,1]
merged[,1] <- NULL

merged is now: 合并现在:

        file1.txt file2.txt file3.txt
1111111         1         0         1
2222222         0         1         1
3333333         1         1         1

See in particular: https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html https://stat.ethz.ch/R-manual/R-devel/library/base/html/merge.html 具体参见: https//stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html https://stat.ethz.ch/R-manual/R-devel /library/base/html/merge.html

And: How to join (merge) data frames (inner, outer, left, right)? 并且: 如何连接(合并)数据框(内部,外部,左侧,右侧)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM