Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

r - storing the difference of values as changes

I want to store the differences and no differences in values into another dataframe when minusing one dataframe from the other.

For example, given this dataset:

> change
   water water2
1      1      1
2      1      2
3      1      2
4      1      1
5      2      2
6      6      4
7      5      4
8      7      5
9      8      9
10     5      5
11     4      2
12     5      5
13     3      3
14     3      3
15     0      2
16     0      0
17     0      0

when performing this calculation:

water2-water

When there is a negative difference, such that water > water2, assign the value -1. When there is a positive difference, such that water < water2 assign the value 1. Otherwise, if there's no difference, then assign the value 0.

Although, I prefer this to be done when the two dataframes are separate and not in a single data, such that:

y2010 <- water2
y2019 <- water

I'm working with a larger dataframe, and would prefer to perform a calculation like above and store those differences in a new dataframe.

reproducible example:

y2010 <- structure(list(water = c(1, 1, 1, 1, 2, 6, 5, 7, 8, 5, 4, 5, 
3, 3, 0, 0, 0)), class = "data.frame", row.names = c(NA, -17L
))

y2019 <- structure(list(water2 = c(1, 2, 2, 1, 2, 4, 4, 5, 9, 5, 2, 5, 
3, 3, 2, 0, 0)), class = "data.frame", row.names = c(NA, -17L
))
question from:https://stackoverflow.com/questions/65833499/storing-the-difference-of-values-as-changes

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the sign function. If the difference is positive it returns 1, it it's negative it returns -1, and if it's 0 it returns 0:

df <- data.frame(change = sign(y2019$water2 - y2010$water))

 change
1       0
2       1
3       1
4       0
5       0
6      -1
7      -1
8      -1
9       1
10      0
11     -1
12      0
13      0
14      0
15      1
16      0
17      0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...