# How to find the number of times a variable changes its sign in an R data frame column?

R ProgrammingServer Side ProgrammingProgramming

To find the number of times a variable changes its sign in an R data frame column, we can use sign function with diff and sum function.

For example, if we have a data frame called df that contains a column say C then, we can find the number of times C changes its sign by using the following command −

## Output

If you execute all the above given snippets as a single program, it generates the following output −

[1] 9


## Example 2

Following snippet creates a sample data frame −

y<-sample(-2:2,20,replace=TRUE)
df2<-data.frame(y)
df2

The following dataframe is created −

    y
1  -1
2   0
3  -1
4   2
5   2
6   0
7   1
8   1
9   1
10  2
11  0
12 -2
13 -1
14 -2
15 -1
16  2
17  0
18  1
19  1
20 -2

To find the number of times y changes its sign, add the following code to the above snippet −

y<-sample(-2:2,20,replace=TRUE)
df2<-data.frame(y)

## Output

If you execute all the above given snippets as a single program, it generates the following output −

[1] 8

Published on 23-Nov-2021 05:22:20