如何删除 R DataFrame 中的行?
在本文中,我们将讨论如何在 R 编程语言中从数据框中删除行。
方法一:按编号删除行
通过使用特定的行索引号,我们可以删除行。
语法:
data[-c(row_number), ]
在哪里。
- 数据是输入数据框
- row_number 是行索引位置
例子:
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing 4 th row
print(data[-c(4), ])
# display by removing 5 th row
print(data[-c(5), ])
# display by removing 1 st row
print(data[-c(1), ])
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing row from 1 st to 4 th
print(data[-c(1:4), ])
# display by removing row from 1 st to 2 nd
print(data[-c(1:2), ])
R
# create a dataframe
data = data.frame(name=c("manoj", "manoja", "manoji", "mano",
"manooj"), age=c(21, 23, 21, 10, 22))
# display by removing 1,3,4 rows
print(data[-c(1, 3, 4), ])
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing age less than 21
print(subset(data,age>21 ))
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing age less than 21
print(na.omit(data))
输出:
> print(data[-c(4), ])
name age
1 manoj 21
2 manoja 23
3 manoji 21
5 manooj 22
> print(data[-c(5), ])
name age
1 manoj 21
2 manoja 23
3 manoji 21
4 mano 10
> print(data[-c(1), ])
name age
2 manoja 23
3 manoji 21
4 mano 10
5 manooj 22
我们还可以使用切片运算符删除多行
语法:
data[-c(row_number_start:row_number_end), ]
在哪里,
- 数据是输入数据框
- row_number_start 是起始行号
- row_number_end 是结束行号
例子:
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing row from 1 st to 4 th
print(data[-c(1:4), ])
# display by removing row from 1 st to 2 nd
print(data[-c(1:2), ])
输出:
name age
5 manooj 22
>
> # display by removing row from 1 st to 2 nd
> print(data[-c(1:2), ])
name age
3 manoji 21
4 mano 10
5 manooj 22
我们还可以通过指定多个行索引来删除多行
语法:
data[-c(row numbers), ]
例子:
R
# create a dataframe
data = data.frame(name=c("manoj", "manoja", "manoji", "mano",
"manooj"), age=c(21, 23, 21, 10, 22))
# display by removing 1,3,4 rows
print(data[-c(1, 3, 4), ])
输出:
name age
2 manoja 23
5 manooj 22
方法 2:有条件地删除行
我们还可以使用 subset()函数来使用条件
句法:
subset(dataframe,condition )
例子:
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing age less than 21
print(subset(data,age>21 ))
输出:
name age
2 manoja 23
5 manooj 22
方法 3:删除具有 NA 值的行:
我们可以使用 na.omit()函数从给定的数据框中删除包含 NA 值的行。
句法:
na.omit(dataframe)
例子:
R
# create a dataframe
data=data.frame(name=c("manoj","manoja","manoji","mano","manooj"),
age=c(21,23,21,10,22))
# display by removing age less than 21
print(na.omit(data))
输出:
name age
1 manoj 21
2 manoja 23
3 manoji 21
4 mano 10
5 manooj 22