R select row of data frame interactively

半世苍凉 提交于 2019-12-10 16:48:35

问题


I have a data frame, say:

df <- data.frame(a=1:10,b=runif(10))

I'd like to be able to display the data frame to the user and have them select (click) a row, and retrieve that row.

Something a bit like edit(df), except that what I want is much simpler in that I don't need editing functions --- I just need to listen for a click event on one of the rows and get the index for that row (I don't even need the particular cell!)

Does anyone know how I can do this? I'd prefer to do it with base R or grid (for the sake of not adding in lots of packages) -- maybe I can somehow draw the data frame on a grid graphics with a y scale defined from 1 to nrow(df) and use the grid.locator() function?

It'd be nice to avoid bringing in gui packages, but if I do, it should be cross-platform (linux/windows). gwidgets is quite nice (although they don't seem to have the click event nicely integrated with their gdf widget).

cheers.


回答1:


well, here's a quick way, no extra packages, but you may have to fiddle with formatting if you want the table to be nicely aligned, rounded, etc:

    df <- data.frame(a=1:10,b=runif(10))
    df[menu(apply(df,1,paste,collapse="  "),graphics=TRUE),]

The device widens itself if necessary and scrollbars automatically appear when necessary.




回答2:


I was going to suggest a combination of a blank plot filled with addtable2plot and then use locator to pick a point and calculate the row with a combination the y-specification and the cellheight <- max(strheight(c(column.names, row.names, as.vector(unlist(table))),... but effort in that direction seems silly since @timrifle seems to have hit the nail on the head.



来源:https://stackoverflow.com/questions/9176125/r-select-row-of-data-frame-interactively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!