How to run a for loop between two columns

I'm new to r programming and I have a csv file which contains a table with two columns: Subject/Subject ID and Age. I want to run a for loop where it checks the age and if it matches the age, then it will return it's corresponding Subject ID. Can someone help me with this. Thanks in advance

Subject ID Age
001-A 10
002-B 15
003-C 20
004-D 25
005-E 30
006-F 35
007-G 40

Your question is not clear but I think you want to know the Subject ID that corresponds to a given Age. The following code shows two ways to get that, neither using a for loop. Note that the first method returns a vector and the second method returns a data frame.

DF <- data.frame(Subject_ID = c("001-A", "002-B", "003-C", "004-D"),
                 Age = c(10, 15,20,25))
DesiredAge = 15

#First method
IDS <- DF[DF$Age == DesiredAge, "Subject_ID"]
IDS
#> [1] "002-B"

#Second method
library(dplyr)

IDS2 <- DF |> filter(Age == DesiredAge) |> select(Subject_ID)
IDS2
#>   Subject_ID
#> 1      002-B

Created on 2022-09-16 with reprex v2.0.2

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.