How to Use the View() Function in R (With Examples)


The View() function in R can be used to invoke a spreadsheet-style data viewer within RStudio.

This function uses the following syntax:

View(df)

Note: Make sure you type a capital “V” when using this function.

The following example shows how to use this syntax in practice.

How to Use the View() Function

We can use the following code to create a data frame in R with 100 rows and 2 columns:

#make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(x=rnorm(100),
                 y=rnorm(100))

We can then use the View() function to invoke a spreadsheet-style data viewer within RStudio:

Notice that a new tab appears in Rstudio that provides an interactive display of the data frame we just created:

At the bottom of the viewer, we can see the size of the data frame: 100 entries (i.e. rows) and 2 columns.

How to Sort Data Using the View() Function

We can also quickly sort the data frame by clicking on one of the columns.

For example, if I click on the header for column x then the rows of the data frame will automatically be sorted from smallest to largest based on the values in column x:

If I click on the header for column x again, the data frame will then be sorted by column x from largest to smallest:

How to Filter Data Using the View() Function

I can also quickly filter the data frame by clicking the Filter icon, then clicking one of the column names, then typing in a range of values.

For example, I may choose to filter the data frame to only show the rows where x is between 0 and 1:

Once I press enter, the data frame will automatically be filtered:

At the bottom of the screen we can see that 33 rows have values in the x column between 0 and 1.

Note that I can also add a filter in the y column to filter by specific values in both x and y.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use match() Function in R
How to Use summary() Function in R
How to Use the table() Function in R
How to Use the quantile() Function in R

Leave a Reply

Your email address will not be published.