How to print the head (first 10 rows) with only select variables in R

Viewed 10903

To print out the first 10 rows of a dataframe in R, I am using head(data.frame, 10).

But this dataframe has 64 variables, and I only want to select 3 of those variables to show for my print out of the first 10 rows.

Can I use the head function to do this?

3 Answers

You can use dplyr::select first and then run head after that in a pipe :)

df <- data.frame(x = rnorm(100, mean = 1, sd = 0.5),
           y = rnorm(100, 30, 2),
           z = rnorm(100, 200, 20))


df %>% 
  select(x, y) %>% 
  head(., 10)

Try this. Might be what you're looking for :

# prints out the first 10 rows of the first 3 columns (or whichever you select by index
head(df[,1:3], 10)

A base-R approach could be something like

df <- data.frame(x = rnorm(100, mean = 1, sd = 0.5),
           y = rnorm(100, 30, 2),
           z = rnorm(100, 200, 20))

head(df[,1:2],10) #1st and 2nd columns
head(df[,c(1,3)],10) #1st and 3rd columns
Related