[英]Using indexing to perform mathematical operations on data frame in r
I'm struggling to perform basic indexing on a data frame to perform mathematical operations.我正在努力对数据框执行基本索引以执行数学运算。 I have a data frame containing all 50 US states with an entry for each month of the year, so there are 600 observations.我有一个包含美国所有 50 个州的数据框,其中包含一年中每个月的条目,因此有 600 个观察值。 I wish to find the difference between a value for the month of December minus the January value for each of the states.我希望找到每个州 12 月份的值减去 1 月份的值之间的差值。 My data looks like this:我的数据如下所示:
> head(df)
state year month value
1 AL 2020 01 2.7
2 AK 2020 01 5
3 AZ 2020 01 4.8
4 AR 2020 01 3.7
5 CA 2020 01 4.2
7 CO 2020 01 2.7
For instance, AL has a value in Dec of 4.7 and Jan value of 2.7 so I'd like to return 2 for that state.例如,AL 在 Dec 的值为 4.7,Jan 的值为 2.7,因此我想为该状态返回 2。
I have been trying to do this with the group_by and summarize functions, but can't figure out the indexing piece of it to grab values that correspond to a condition.我一直在尝试使用 group_by 和 summary 函数来做到这一点,但无法弄清楚它的索引部分来获取与条件相对应的值。 I couldn't find a resource for performing these mathematical operations using indexing on a data frame, and would appreciate assistance as I have other transformations I'll be using.我找不到使用数据框上的索引来执行这些数学运算的资源,我将不胜感激,因为我将使用其他转换。
With dplyr
:使用dplyr
:
library(dplyr)
df %>%
group_by(state) %>%
summarize(year_change = value[month == "12"] - value[month == "01"])
This assumes that your data is as you describe--every state has a single value for every month.这假设您的数据如您所描述的那样——每个州每个月都有一个值。 If you have missing rows, or multiple observations in for a state in a given month, I would not expect this code to work.如果您在给定月份的某个州缺少行或多次观察,我不希望此代码起作用。
Another approach, based row order rather than month value, might look like this:另一种基于行顺序而不是月份值的方法可能如下所示:
library(dplyr)
df %>%
## make sure things are in the right order
arrange(state, month) %>%
group_by(state) %>%
summarize(year_change = last(value) - first(value))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.