Delete Rows based on a Column in Data Frame
To delete rows of a data frame in R, based on a column, use the following expression.
data_frame_name <- data_frame_name[ !condition, ]
Please observe the NOT operator before the condition.
data_frame[condition, ]
returns the rows that satisfy the condition. So, if we negate the condition, the rows that satisfy this condition are dropped, and the rest of the rows shall be returned as a data frame.
Examples
Delete Rows where Column Value is greater than Specific Value
In the following example, we take a data frame in df
, and delete the rows of this data frame based on the column age
, where the column value is greater than specific value age > 10
.
example.r
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
age = c(4, 8, 10, 14, 18, 10, 12),
income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))
df <- df[! df['age'] > 10, ]
print(df)
Output
tutorialkart$ Rscript example.r
name age income
1 A 4 1.6
2 B 8 1.5
3 C 10 1.7
6 F 10 1.0
Delete Rows where Column Value is equal to Specific Value
In the following example, we take a data frame in df
, and delete the rows of this data frame based on the column age
, where the column value is equal to specific value age == 10
.
example.r
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
age = c(4, 8, 10, 14, 18, 10, 12),
income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))
df <- df[! df['age'] == 10, ]
print(df)
Output
tutorialkart$ Rscript example.r
name age income
1 A 4 1.6
2 B 8 1.5
4 D 14 1.9
5 E 18 1.5
7 G 12 1.7
Delete Rows where Column Value is less than Specific Value
In the following example, we take a data frame in df
, and delete the rows of this data frame based on the column age
, where the column value is less than specific value age < 10
.
example.r
df <- data.frame(name = c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
age = c(4, 8, 10, 14, 18, 10, 12),
income = c(1.6, 1.5, 1.7, 1.9, 1.5, 1.0, 1.7))
df <- df[! df['age'] < 10, ]
print(df)
Output
tutorialkart$ Rscript example.r
name age income
3 C 10 1.7
4 D 14 1.9
5 E 18 1.5
6 F 10 1.0
7 G 12 1.7
We can use other relational operators as well like Not-Equal-to, Greater than or equal to, Less than or equal to, etc., in forming the condition.
Conclusion
In this R Tutorial, we learned how to delete the rows of a data frame based on the values of a single column, with the help of an example programs.