R语言 数据框架行和列分段
通过简单地使用索引或切片操作符来提取数据集中的行和列信息的过程被称为 切片。
在R编程中,行和列可以通过两种方式进行切片,即使用索引或使用行和列的名称。如果行或列的索引或名称是已知的,那么切片操作符在提取时就更有用。使用slice操作符对数据帧进行切片,比使用dplyr包中的slice()方法对数据集进行切片更有效。
语法: dataframe[start_row:end_row,start_column:end_column]
加载数据集
在R中加载默认的数据集iris并将其转换为数据帧。
# Load the iris dataset
data(iris)
# Convert the data set to data frame
df <- data.frame(iris)
例子
让我们看看上述数据集的一些切片例子。
以这样的方式对数据框进行切片,只提取第3行的 数据。
# To extract all the columns of row number 3 records
df[3,]
输出
对数据框进行切片,提取第5行至第10行的所有列。
# To extract all the columns from row number 5 to 10
df[5:10,]
输出
对数据框进行切片,提取第5列和所有行。
# To extract 5th column and all the rows of it
df[,5]
输出
对数据框进行切片,提取第2至第5行的第3和第5列数据。
# To extract the 3rd and 5th column
# data present from 2nd to 5th row
df[2:5,3:5]
输出