简体   繁体   中英

How to save character output in loop?

So I made this function, that only takes one numerical element, not a vector.

salaryCategory=function(s){
  if(s>=40000 && s<70000)
    print("Low")
  if(s>=70000 && s<100000)
    print("Medium")
  if(s>=100000 && s<140000)
    print("High")
  if(s<40000 || s>=140000)
    print("Invalid")
}

Now Im trying to save output using this function inside of a vector.

My goal is to use a loop and use this function to make a another vector with output from the function.

When I try to run this.

k=c(500000,75000,100000,42000)
j=c()
for (i  in 1:length(k)) {
  
  
  j[i]=salaryCategory(k[i])
  
  
}




The output Im going for is to save the out put from the function inside "j" so what I want it to look like is this.


j=("invalid","Medium","High","Low")

Its not saving the code inside of j and I dont know what I'm doing wrong.

In R , for if/else/... statement, format is like

if (condition) {
  action
}

And to give an input, print is not appropriate.

Therefore, your function should be

salaryCategory=function(s){
  if(s>=40000 && s<70000){
    ("Low")
  } else if
  (s>=70000 && s<100000) {
    ("Medium")
  } else if (s>=100000 && s<140000) {
    ("High")
  } else if (s<40000 || s>=140000) {
    ("Invalid")
  }
    
}

And for j ,

j=c()
for (i  in 1:length(k)) {
  j <- c(j, salaryCategory(k[i]))
}
j

[1] "Invalid" "Medium"  "High"    "Low" 

Your way for j works too.

j=c()
for (i  in 1:length(k)) {
  
  
  j[i]=salaryCategory(k[i])
  
  
}
j

[1] "Invalid" "Medium"  "High"    "Low"   

You need to use return in your function instead of print

salaryCategory=function(s){
  if(s>=40000 && s<70000)
    return("Low")
  if(s>=70000 && s<100000)
    return("Medium")
  if(s>=100000 && s<140000)
    return("High")
  if(s<40000 || s>=140000)
    return("Invalid")
}

You can use the cut() function and avoid the nested if statements.

 #test data
 s<-c(0, 50000, 80000, 110000, 200000)

 cut(s, breaks=c(-Inf, 40000, 70000, 100000, 140000, Inf),
       labels=c("invalid", "Low", "Medium", "High", "invalid") )

your code in function salaryCategory has response output value without save the value, you must change output to return value in function salaryCategory with code

salaryCategory <- function(x) {
if(s>=40000 && s<70000)
    return ("Low")
  if(s>=70000 && s<100000)
    return ("Medium")
  if(s>=100000 && s<140000)
    return ("High")
  if(s<40000 || s>=140000)
    return ("Invalid")
}

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