mathematical.coffee
mathematical.coffee

Reputation: 56915

R select row of data frame interactively

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.

Upvotes: 4

Views: 1271

Answers (2)

IRTFM
IRTFM

Reputation: 263381

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.

Upvotes: 0

tim riffe
tim riffe

Reputation: 5691

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.

Upvotes: 8

Related Questions