如何删除 R DataFrame 中的行?
在本文中,我们将看到如何在 R 编程语言中从 Dataframe 中删除行。
删除单行
为此,要删除的行的索引用减号传递。
句法:
df[-(index), ]
示例 1:
R
# creating a data frame with
# some data .
df=data.frame(id=c(1,2,3),
name=c("karthik","sravan","nikhil"),
branch=c("IT","IT","CSE"))
# using - with indexing deleting
# 3rd row .
df[-3,]
R
# creating a data frame with
# some data .
df=data.frame(id=c(1,2,3),
name=c("karthik","sravan","nikhil"),
branch=c("IT","IT","CSE"))
# using - with indexing deleting
# 2nd row
df[-2,]
R
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
# deleting multiple rows using
# vector
df[-c(3,5),]
R
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
# deleting multiple rows using
# vector
df[-c(2,4),]
R
library(dplyr)
# creating a data frame with some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
anti_join(df,df[c(1,2),])
R
library(dplyr)
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
anti_join(df,df[c(1,3),])
输出 :
示例 2:
电阻
# creating a data frame with
# some data .
df=data.frame(id=c(1,2,3),
name=c("karthik","sravan","nikhil"),
branch=c("IT","IT","CSE"))
# using - with indexing deleting
# 2nd row
df[-2,]
输出 :
删除多行
方法 1:使用范围
为此,要删除的行的范围将传递给数据框名称。
句法:
df[-(start_index,end_index), ]
示例 1:
电阻
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
# deleting multiple rows using
# vector
df[-c(3,5),]
输出:
示例 2:
电阻
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
# deleting multiple rows using
# vector
df[-c(2,4),]
输出 :
方法二:使用anti_join()
anti_join 方法在 dplyr 包中可用。所以我们必须先安装 dplyr 包。要安装我们可以使用 install.package() 方法,我们必须将包名作为参数传递。要将包导入到 R 环境中,我们需要使用 library()函数。在这个函数,我们必须将包名作为参数传递。
句法 :
anti_join (data_frame_name , data_frame_name [ c(row_index 1 ,…row_index n),c( column_index 1,……column_index n)] )
示例 1:
电阻
library(dplyr)
# creating a data frame with some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
anti_join(df,df[c(1,2),])
输出 :
示例 2:
电阻
library(dplyr)
# creating a data frame with
# some data
df=data.frame(id=c(1,2,3,4,5),
name=c("karthik","sravan","nikhil",
"bhagiradh","sai"),
branch=c("IT","IT","CSE","IT","CSE"))
anti_join(df,df[c(1,3),])
输出 :