Remove rows that contain negative value in column

Hi,
I have a data frame, where some of the values are negative in debt column.

company<-c("comp1","comp1","comp2","comp2","comp2","comp3","comp3")
year<-c(2010,2011,2010,2011,2012,2009,2010)
MV<-c(12,54,23,54,66,54,34)
price<-c(43,34,43,54,65,34,65)
debt<-c(54,54,56,-12,54,23,45)
df<-data.frame(company,year,MV,price,debt)

My question is: I want to remove the companies that have negative "debt" values. That is, not just remove the row with the negative value, but remove all of the observations of company 2 (as there is one (or more) year with negative value).

Thanks!

So you need to find out if any of the debts for a company has negative debt. To do this, I group the records by company and then remove records where at least one has a negative debt using the logic specified in the script below:

company<-c("comp1","comp1","comp2","comp2","comp2","comp3","comp3")
year<-c(2010,2011,2010,2011,2012,2009,2010)
MV<-c(12,54,23,54,66,54,34)
price<-c(43,34,43,54,65,34,65)
debt<-c(54,54,56,-12,54,23,45)
df<-data.frame(company,year,MV,price,debt)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df %>%
  group_by(company) %>%
  filter(!any(debt<0))
#> # A tibble: 4 x 5
#> # Groups:   company [2]
#>   company  year    MV price  debt
#>   <chr>   <dbl> <dbl> <dbl> <dbl>
#> 1 comp1    2010    12    43    54
#> 2 comp1    2011    54    34    54
#> 3 comp3    2009    54    34    23
#> 4 comp3    2010    34    65    45

Created on 2022-03-13 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.