简体   繁体   中英

Print a R function that loop through 3 arguments and output matching criteria

I have an excel file that includes student names, zip code, gender, and major. It needs to be written in a function that takes in 3 arguments d for the data (the excel file), z for the zip, and m for the major. The function has to loop through each row in the data and when I call the function, it will print out the names of the student matching zip and major I put in. For example, student_data(student, 12345, Music) will print out:

Names   Zip    Major   Gender
John    12345  Music   Male
Jane    12345  Music   Female

Here is my code:

library(readxl)
student <- read_excel("student")

student_data <- function(d, s, m){
  d <- student
  s <- d$studentname
  m <- d$major
  for (i in 1:nrow(d)){
    return(subset(d, s[i] & m[i])
  }
}

student_data(d, 12345, "Music")

When I call this, the output is NULL.

Try the following function. The input is changed to have z (for Zip ), not s . It returns a subset of d matching the given criteria.

student_data <- function(d, z, m){
  i <- d[["Zip"]] == z
  j <- d[["Major"]] == m
  d[i & j, ]
}

If the function needs to accept several values for z or m , rewrite it as

student_data <- function(d, z, m){
  i <- d[["Zip"]] %in% z
  j <- d[["Major"]] %in% m
  d[i & j, ]
}

You're making simple syntax mistakes here.

  1. When you use return , you're telling the function to end right there, so it does not make sense to have a return inside a loop, because you're only returning the first iteration.

  2. Your function takes s and m as inputs, but then overwrites them with information found in d , which means they are not used as inputs at all. I'm assuming you actually want to take as inputs (d, z, m) right?

  3. If you want to print the rows where there are students with Zip z which are enrolled in the m major, you could just filter the dataset and print it altogether in two lines. For example:

student_data <- function(d, z, m) {
    # select all rows where Zip = z and major == m
    d_filtered <- d[d$Zip == z & d$major == m, ]

    print(d_filtered)
}

NOTE: The answer may not be totally right because your example provided is a bit confusing. Please edit your question and provide more details if that is the case and I will edit my answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM