在 R 中提取最后 N 行数据帧
可以使用 R 中内置的 tail()方法访问数据帧的最后 n 行。 假设,N 是数据帧中的总行数,那么可以从结构体。
Syntax:
tail(dataframe, n = )
Parameter :
- dataframe – The data frame to extract rows from the end
- n – integer which indicates the number of rows to extract.
更改不会保留到原始数据框中。就要提取的行数而言,时间复杂度是多项式的,即值 n。
方法
- 创建数据框
- 将所需的行数传递给 tail()
- 提取行
- 显示结果
示例 1:
R
# declaring data frame
data_frame = data.frame(
col1 = c(1:6),
col2 = c(7:12),
col3 = c(13:24))
# printing original data frame
print ("Original Data Frame")
print(data_frame)
# extracting last row from the data frame
last_row = tail(data_frame, n =1)
# printing the last row of the data frame
print ("Extracting last row from data frame")
print (last_row)
R
# declaring data frame
data_frame = data.frame(
col1 = c(1:6),
col2 = c(7:12),
col3 = c(13:24))
# printing original data frame
print ("Original Data Frame")
print(data_frame)
# extracting last row from the data frame
last_4row = tail(data_frame, n = 4)
# printing the last row of the data frame
print ("Extracting last 4 rows from data frame")
print (last_4row)
R
# declaring data frame
data_frame = data.frame(
col1 = c(1:3),
col2 = c(7:9),
col3 = c(13:15))
# printing original data frame
print ("Original Data Frame")
print(data_frame)
# extracting all rows from the data frame using nrow() method
df = tail(data_frame, n = nrow(data_frame))
# printing the last row of the data frame
print ("Extracting last rows from data frame")
print (df)
输出
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
4 4 10 16
5 5 11 17
6 6 12 18
7 1 7 19
8 2 8 20
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
[1] "Extracting last row from data frame"
col1 col2 col3
12 6 12 24
示例 2:
电阻
# declaring data frame
data_frame = data.frame(
col1 = c(1:6),
col2 = c(7:12),
col3 = c(13:24))
# printing original data frame
print ("Original Data Frame")
print(data_frame)
# extracting last row from the data frame
last_4row = tail(data_frame, n = 4)
# printing the last row of the data frame
print ("Extracting last 4 rows from data frame")
print (last_4row)
输出
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
4 4 10 16
5 5 11 17
6 6 12 18
7 1 7 19
8 2 8 20
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
[1] "Extracting last 4 rows from data frame"
col1 col2 col3
9 3 9 21
10 4 10 22
11 5 11 23
12 6 12 24
nrow() 方法可用于提取数据框中的总行数。当我们将它作为 n 的参数值传递时,所有的行都被提取出来。
示例 3:
电阻
# declaring data frame
data_frame = data.frame(
col1 = c(1:3),
col2 = c(7:9),
col3 = c(13:15))
# printing original data frame
print ("Original Data Frame")
print(data_frame)
# extracting all rows from the data frame using nrow() method
df = tail(data_frame, n = nrow(data_frame))
# printing the last row of the data frame
print ("Extracting last rows from data frame")
print (df)
输出
[1] "Original Data Frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15
[1] "Extracting last rows from data frame"
col1 col2 col3
1 1 7 13
2 2 8 14
3 3 9 15