Reputation: 1970
Given that you have a data frame with a lot of columns and rows, how can you visualize this in a good way?
I have imported my data from excel, where I in a clear way can browse my data. However, when I import it as a data frame into R, things get more complicated. I quickly get lost in the output in my terminal window. Could I output my data frame into some form of more easily accessible form for viewing, something that looks more the way it would look in excel?
Upvotes: 5
Views: 3733
Reputation: 4371
You can use DT, an R interface to the DataTables library.
Here is a quick function to visualize a dataframe in your browser:
viewdf <- function(df,
to_truncate = NULL,
truncate_max = 10,
truncate_max_title = 200,
types_in_colnames = TRUE,
filter = "top",
to_round = NULL,
to_round_digits = 2) {
# column names to display
newcolnames <- colnames(df)
for (i in seq(1, length(newcolnames))) {
newcolnames[i] <- stringr::str_replace_all(newcolnames[i], "_", " ")
}
if (types_in_colnames) {
for (i in seq(1, length(colnames(df)))) {
col <- colnames(df)[i]
newcolnames[i] <- paste0(
newcolnames[i],
"\n{",
class(df[[col]]),
"}"
)
}
}
# We need to replace NA values with a character value
# for columns we are going to truncate,
# otherwise DT crashes and show an empty table
to_truncate_ix <- which(colnames(df) %in% to_truncate)
l <- list()
for (el in to_truncate) {
l[[el]] <- "NA"
}
df %<>% tidyr::replace_na(l)
# Generate DT table
dtobj <- DT::datatable(df,
colnames = newcolnames,
filter = filter,
options = list(
pageLength = 20,
filter = "top",
autoWidth = TRUE,
columnDefs = list(list(
targets = to_truncate_ix,
render = DT::JS(
"function(data, type, row, meta) {",
"return type === 'display' && ",
"data.length > ", truncate_max, " ?",
"'<span title=\"' + ",
"data.substr(0,", truncate_max_title, ") + ",
"'...\">' + ",
"data.substr(0, ", truncate_max, ") + ",
"'...</span>' : data;",
"}"
)
))
)
)
# Round number columns
for (col in to_round) {
dtobj %<>% DT::formatRound(col, to_round_digits)
}
return(dtobj)
}
Upvotes: 0
Reputation: 29367
RStudio does a pretty good job with its built-in (read-only) data viewer. Other solutions have been suggested on Cross Validated: Is there a good browser/viewer to see an R dataset (.rda file).
Upvotes: 5
Reputation: 89057
You can use edit(my.data.frame)
.
It will open your data.frame into the default editor specified by getOption("editor")
. You can use option(editor = ".......")
to change that default, or just use the editor=
option when calling edit
. This is only relevant for Unix users.
Finally, I'll bring your attention to this important portion of the ?edit
documentation:
It is important to realize that
edit
does not change the object called name. Instead, a copy ofname
is made and it is that copy which is changed. Should you want the changes to apply to the objectname
you must assign the result ofedit
toname
. (Tryfix
if you want to make permanent changes to an object.)
Upvotes: 5