How do I run a for loop to detect a row in respect to a value within this dataframe in R?

Hi, I am new to R and trying to learn with a project:

#My dataset repex(cityincdiff):

zip    total_a  Difference       City
000650  15            2         Philly
990112  16        17777         Newyork

I want to write a function that returns the city with respect to the Difference column:

I tried using a for loop but I am stuck:

for (i in cityincdiff){
print City if Difference == 17777)

#Desired Output:


Is there a better way to do it rather than a for loop?if not how do I correct my for loop?

for( i in 1:nrow(cityincdiff)){

if(cityincdiff$Difference[i] == 17777){

And yes, there is a better way to do it:

cityincdiff$City[cityincdiff$Difference == 17777]


of you could use dplyr and do:


cityincdiff %>%
    filter(Difference == 17777) %>%

I happen to like the dplyr syntax quite a lot and I find it easy to read.

1 Like

In addition, if you would like to use the function subset(...) from base R.

cityincdiff <- data.frame(zip=c('000650','990112'),
                          stringsAsFactors = FALSE)

subset(x = cityincdiff, subset = Difference==17777, select = 'City')
#>      City
#> 2 Newyork

subset(x = cityincdiff, subset = Difference==17777, select = 'City', 
       drop = TRUE)
#> [1] "Newyork"

Created on 2019-03-20 by the reprex package (v0.2.1)

Best regards

This topic was automatically closed 7 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.