R head() and tail() Functions - View the Beginning and End of Data

R 语言实例R Language Examples

The R head() function is used to view the first few rows of data, and tail() views the last few rows.

These two functions are the first step in data exploration, used to quickly understand the structure of the data.

The syntax of the head() and tail() functions is as follows:

head(x, n = 6)
tail(x, n = 6)

Parameter description:

  • xInput object (vector, data frame, matrix, etc.).

  • nThe number of rows to display, default is 6.

Examples

# Generate a large data frame
set.seed(123)
df <- data.frame(
Number= 1:100,
Score= round(rnorm(100, mean = 70, sd = 15), 1)
)
print("First 10 rows:")
print(head(df, 10))

print("Last 5 rows:")
print(tail(df, 5))

The output of executing the above code is:

[1] "前 10 行:"
   编号 分数
1     1 61.6
2     2 66.5
3     3 93.4
4     4 71.1
5     5 71.9
6     6 95.7
7     7 76.9
8     8 51.0
9     9 59.7
10   10 63.3
[1] "后 5 行:"
    编号 分数
96    96 70.9
97    97 53.3
98    98 62.1
99    99 64.1
100  100 78.9

R 语言实例R Language Examples

Other Extensions