Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run if statements on a dataframe in a for loop in R

I have a problem which i haven’t been able to find a solution for on here.
I have a dataframe which, very simplified, would look something like this (Is actually 50k x 12):

tag:   1273 1273 1273  1275  1275 1278  1278

dist:
   1002
   3212
   1252
  2152
    232
    582
    752

I need a for loop that basically prints out the number of times a number is bigger than e.g 1000.
So that i preferably end up with a vector that says

tag:  1273 1275 1278

amount:   3  1  0

I haven’t worked with loops in R before, only python, so any help is appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s difficult to guess what your intended outcome looks like; is this what you’re trying to do?

library(dplyr)

df <- data.frame(tags = c(1273,1273,1273,1275,1275,1278,1278),
                 dist = c(1002,3212,1252,2152,232,582,752))

df %>%
  group_by(tags) %>%
  tally(dist > 1000, name = "amount") 
#> # A tibble: 3 × 2
#>    tags amount
#>   <dbl>  <int>
#> 1  1273      3
#> 2  1275      1
#> 3  1278      0

# output as a vector
df %>%
  group_by(tags) %>%
  tally(dist > 1000, name = "amount") %>%
  pull(amount, tags)
#> 1273 1275 1278 
#>    3    1    0

Created on 2022-09-05 by the reprex package (v2.0.1)

If this isn’t correct, what changes need to be made?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading