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:
#Input:

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

#Desired Output:

"Newyork"

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){
print(cityincdiff$City[i])
}
}

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

cityincdiff$City[cityincdiff$Difference == 17777]

3 Likes

of you could use dplyr and do:

library(tidyverse)

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

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'),
                          total_a=c(15,16),
                          Difference=c(2,17777),
                          City=c('Philly','Newyork'),
                          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
Adam

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.