[英]How to create a table in R populated with 1s and 0s to show presence of values from another table?
[英]How to create a table in R with 1s and 0s based on the presence of values from several other files
我有五个不同的文本文件,都包含7位数行。 我想创建一个表,告诉我,使用1和0,该行是否存在于文件中。
例如:
file1.txt file2.txt file3.txt
xxxxxxx 1 0 1
xxxxxxx 0 1 1
xxxxxxx 1 1 1
我对R或任何编码都没什么经验。 有人能帮我吗? 如果有人问,我可以添加更多信息。
假设存在三个文件:
==> file1.txt <==
1111111
3333333
==> file2.txt <==
2222222
3333333
==> file3.txt <==
1111111
2222222
3333333
我会将这三个文件读入单独的数据帧:
file1=read.csv('file1.txt', header=FALSE)
file2=read.csv('file3.txt', header=FALSE)
file3=read.csv('file3.txt', header=FALSE)
为每个添加一个标志:
file1$file1.txt <- rep(1,nrow(file1))
file2$file2.txt <- rep(1,nrow(file2))
file3$file3.txt <- rep(1,nrow(file3))
使用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
合并现在:
file1.txt file2.txt file3.txt
1111111 1 0 1
2222222 0 1 1
3333333 1 1 1
具体参见: 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.