Rocky Singhania
Rocky Singhania

Reputation: 1

how to print the output of multiple function calls in the same line?

condition<-function(temp){

V<-c()

for (i in length(temp)){


if(temp[i]>100){


V[i]<-"Hot"

    }
    else{
        V[i]<-"Normal"
        
    }

}
a<-V[!is.na(V)]


return(a)
}

print(condition(c(101,93,777,110)))


print(condition(c(90,120)))


print(condition(c(97,55,51)))

The Current output is

[1] "Hot"


[1] "Hot"


[1] "Normal"

But I want

[1] "Hot" "Hot" "Normal"

Upvotes: 0

Views: 155

Answers (1)

zephryl
zephryl

Reputation: 17069

First off, your function as written is only using the last element of each vector, rather than returning a value for every element, which is what I assume you want. Instead, use ifelse(), which is vectorized:

condition <- function(temp) {
  V <- ifelse(temp > 100, "Hot", "Normal")
  V[!is.na(V)]
}

condition(c(101,93,777,110))
# [1] "Hot"    "Normal" "Hot"    "Hot"   

If you want a single vector from multiple calls to condition(), combine the results using c():

c(
  condition(c(101,93,777,110)),
  condition(c(90,120)),
  condition(c(97,55,51))
)
# [1] "Hot"    "Normal" "Hot"    "Hot"    "Normal" "Hot"    "Normal" "Normal"
# [9] "Normal"

Upvotes: 1

Related Questions