R 在 txt 文件中写入满足特定条件的所有列名称
R Write in a txt File all column names that meet certain criteria
假设我有以下数据:
A
1 2
term1 0 1
term2 2 3
我想要这样的 txt 文件:
term1 2
term2 1 2
换句话说,我写行名,以及值大于0的列名。
我尝试了以下方法:
filename <- "palabra_documento/mapeo.txt"
fileConn<-file(filename)
rowNames <- rownames(AA.matrix)
for(i in 1:nrow(AA.matrix))
{
line <- names(AA.matrix[i, AA.matrix[i, ] > 0])
line <- c(rowNames[i], line, "\n")
writeLines(paste(line, collapse = " "), fileConn)
}
close(fileConn)
但是它不起作用有两个原因:
- 每次都重写文件(我只能在txt文件中放一行,我的错误)
- 当只有一列符合条件时,它是一个标量值,因此,它的列没有名称。
(A <- matrix(c(0, 2, 1, 3), ncol = 2, dimnames = list(c("term1", "term2"), 1:2)))
# 1 2
# term1 0 1
# term2 2 3
l <- apply(A, 1, function(x) which(x > 0, arr.ind=TRUE, useNames = FALSE))
sink("output.txt")
for (i in 1:length(l))
cat(names(l[i]), paste(l[[i]], collapse = " "), "\n")
sink()
file.show("output.txt")
# term1 2
# term2 1 2
假设我有以下数据:
A
1 2
term1 0 1
term2 2 3
我想要这样的 txt 文件:
term1 2
term2 1 2
换句话说,我写行名,以及值大于0的列名。
我尝试了以下方法:
filename <- "palabra_documento/mapeo.txt"
fileConn<-file(filename)
rowNames <- rownames(AA.matrix)
for(i in 1:nrow(AA.matrix))
{
line <- names(AA.matrix[i, AA.matrix[i, ] > 0])
line <- c(rowNames[i], line, "\n")
writeLines(paste(line, collapse = " "), fileConn)
}
close(fileConn)
但是它不起作用有两个原因:
- 每次都重写文件(我只能在txt文件中放一行,我的错误)
- 当只有一列符合条件时,它是一个标量值,因此,它的列没有名称。
(A <- matrix(c(0, 2, 1, 3), ncol = 2, dimnames = list(c("term1", "term2"), 1:2)))
# 1 2
# term1 0 1
# term2 2 3
l <- apply(A, 1, function(x) which(x > 0, arr.ind=TRUE, useNames = FALSE))
sink("output.txt")
for (i in 1:length(l))
cat(names(l[i]), paste(l[[i]], collapse = " "), "\n")
sink()
file.show("output.txt")
# term1 2
# term2 1 2