Home > Back-end >  How to save character output in loop?
How to save character output in loop?

Time:11-03

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.

CodePudding user response:

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") )

CodePudding user response:

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"   

CodePudding user response:

You need to use return instead of print

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

CodePudding user response:

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")
}
  •  Tags:  
  • r
  • Related