Carl O'Beirne
Carl O'Beirne

Reputation: 329

If a condition is met, add entire row to a new dataframe in R

I am looping though my main data frame to identify where the cost of a night in an Air BnB is > 1000, it will add the entire row to a new dataframe. Currently, it is just adding one row, but I want it to add all of them.

Below is the code that I have

highCost <- data.frame()

for(i in 1:length(AirBnbListingsDublin$price)){
    if(AirBnbListingsDublin$price[i] >= 1000){
        highCost <- data.frame(rbind(AirBnbListingsDublin[i, ]))
    }
}

The row that is added to the new data frame is row 9273 from the main dataframe, but i is working fine, as it loops up until 9437, which is the length of the dataframe

Thanks

Upvotes: 0

Views: 970

Answers (2)

ulfelder
ulfelder

Reputation: 5335

This is really just a filtering task, so you can do something simpler like:

highCost <- AirBnbListingDublin[AirBnbListingsDublin$price >= 1000,]

Or in the tidyverse:

highcost <- dplyr::filter(AirBnbListingDublin, price >= 1000)

Upvotes: 4

ThomasIsCoding
ThomasIsCoding

Reputation: 102625

If you insist on using for loop, then the code below might be the right one you need

highCost <- data.frame()

for(i in 1:length(AirBnbListingsDublin$price)){
  if(AirBnbListingsDublin$price[i] >= 1000){
    highCost <- rbind(highCost,AirBnbListingsDublin[i, ])
  }
}

Otherwise, an easier way should be something like

highCost <- subset(AirBnbListingsDublin, price >= 1000)

Upvotes: 2

Related Questions