在 R 中使用 tcltk 在弹出 window(table 小部件)中显示数据 - 为什么它会删除最后一行数据?

Displaying data in a pop up window (table widget) using tcltk in R - why is it dropping the last row of data?

我正在努力创建一个小部件以使用 tcl/tk 在 window 弹出窗口中查看 table。我正在关注这个例子:http://r.789695.n4.nabble.com/Tck-tk-help-td1837711.html

但是当我 运行 包含我的数据的脚本时,最后一行数据不包含在数组中。这是汽车数据的示例(table 不显示行名称并不重要):

require(tcltk)
tclRequire("Tktable")

toTclArray<-function(dsn,dig=2) { 
 # http://r.789695.n4.nabble.com/Tck-tk-help-td1837711.html
 # Converts Data Frame/Matrix to a Tcl Array for Use in Displaying Tables 
 # dsn is the data set name 
 # dig is the number of digits to round to 
        require(tcltk) 
        tclarray1<-tclArray() 
        for (i in 0:(dim(dsn)[1])) { 
                for (j in 0:(dim(dsn)[2]-1)) { 
                        # First Row is Set to Column Names to be Used as Labels 
                        if (i==0) { 
                                tclarray1[[i,j]]<-colnames(dsn)[j+1] 
                        } else { 
                                tem<-dsn[i,j+1] 
                                tclarray1[[i,j]]<-ifelse(is.na(tem),".", 
                                        ifelse(is.numeric(tem),round(tem,digits=dig), 
                                        as.character(tem))) 
                        } 
                } 
        } 
        return (tclarray1) 
}

temptable <- toTclArray(mtcars)
      tt<-tktoplevel()
      table1 <- tkwidget(tt,"table",variable=temptable,rows=dim(mtcars)[1],
          cols=dim(mtcars)[2],titlerows=1,selectmode="extended",colwidth=10)
          tkgrid(table1, pady = 20, padx = 30)

据我了解,在原始数据集中,第一行数据是第 1 行,第一列数据是第 1 列。在数组中,header 是第 0 行,第 1 行数据是第 1 行,数据的第一列是第 0 列。在 for 循环中,它从第 (i) 行 0 到第 32 行和第 (j) 列 0 到 10。这是有道理的,因为列从 1-11 移动到 0-10,但行不需要更改因为仍然会有 32 行数据。所以我无法弄清楚代码中需要编辑什么才能将最后一行数据添加到 table。

(我确信 运行 这个任务有一个很好的包,但我正在为工作中的项目创建一个界面,我被指示不要使用任何不符合要求的包附带基础 R)

非常感谢任何帮助。谢谢!

这是一个非常简单的修复。您的函数看起来不错,但是您的小部件设置在将行分配给 tk table 时忘记考虑 header 行。只需添加一个 +1 就可以了:

tt<-tktoplevel()
table1 <- tkwidget(tt,"table",variable=temptable,rows=dim(mtcars)[1]+1,
                  cols=dim(mtcars)[2],titlerows=1,selectmode="extended",colwidth=10)
tkgrid(table1, pady = 20, padx = 30)

结果: