'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"
Solution 1:[1]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
