2015-11-06 60 views
1

讓假設我有以下數據:R刻錄符合特定條件的所有列名

A 
     1 2 
term1 0 1 
term2 2 3 

我想要一個txt文件,像這樣的:

term1 2 
term2 1 2 

換句話說,我寫了rowname,以及其中值大於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) 

但是它不適合,原因有二:

  1. 重寫文件每次(我只能把在TXT文件中的一行,我的錯誤)
  2. 當只有一列滿足標準,它是一個標量值,所以,它的列沒有名字。其中只有一個柱,使用`drop`命令的矩陣內,以
+0

嘗試'其中(A> 0,arr.ind = TRUE)' – akrun

+0

此外,對於問題2,在殼體避免將一個列子集強制轉換爲標量,如下所示:'m < - m [1,2,drop = FALSE]' – giraffehere

回答

1
(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 
+1

謝謝!奇蹟般有效! – dpalma

相關問題