I was wondering if someone can help me with this, I need a function that goes trough a vector and recognizes the signs of the numbers inside, thats de basic idea, then I'll try to make some modifications so the function counts every number and shows something like "There are 2 positive numbers and 3 negatives"
How could I make a function thar goes trough a vector and recognizes the signs of the numbers on it?
Asked
Active
Viewed 41 times
0
-
1It'd be helpful if you had an example string or something ... Also: do positive numbers have a `+`sign`? – Chris Ruehlemann Apr 08 '21 at 20:23
-
It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. There's the `sign()` function that can tell you the sign for a number. Or you could do something like `sum(x>0)` and `sum(x<0)` – MrFlick Apr 08 '21 at 20:24
-
1Or `table(x>0)` – M.Viking Apr 08 '21 at 20:24
-
Something like: `x <- c(1,-2,3,-4,5,1,2,3,-7,1,-3,-8,10,-2) sum(x > 0) sum(x < 0)` – Chris Ruehlemann Apr 08 '21 at 20:32
1 Answers
0
What about the following approach (I added also functionality for zeros, remove this feature if it is not needed, or merge it with one of the other two conditions):
sign_function <- function(x){
count_pos_numbers = sum(x>0)
count_neg_numbers = sum(x<0)
count_zeros = sum(x==0)
sprintf("There are %d positive numbers, %d negative numbers, and %d zeros.", count_pos_numbers, count_neg_numbers , count_zeros)
}
I hope that I understood your question correctly.

helios
- 66
- 2