我想按组计算差异。虽然我参考了SO上的R: Function “diff” over various groups线程,但出于未知原因,我无法找到差异。我已经尝试了三种方法:a)
spread
b)使用dplyr::mutate
和base::diff()
c)使用data.table
和base::diff()
。虽然a)可以工作,但我不确定如何使用b)和c)解决这个问题。
关于数据的描述:
我有产品按年份分类的收入数据。我将年份大于等于2013年的数据归类为第二阶段(称为P2
),而年份小于2013年的数据归类为第一阶段(称为P1
)。
样本数据:
dput(Test_File)
structure(list(Ship_Date = c(2010, 2010, 2012, 2012, 2012, 2012,
2017, 2017, 2017, 2016, 2016, 2016, 2011, 2017), Name = c("Apple",
"Apple", "Banana", "Banana", "Banana", "Banana", "Apple", "Apple",
"Apple", "Banana", "Banana", "Banana", "Mango", "Pineapple"),
Revenue = c(5, 10, 13, 14, 15, 16, 25, 25, 25, 1, 2, 4, 5,
7)), .Names = c("Ship_Date", "Name", "Revenue"), row.names = c(NA,
14L), class = "data.frame")
预期输出
dput(Diff_Table)
structure(list(Name = c("Apple", "Banana", "Mango", "Pineapple"
), P1 = c(15, 58, 5, NA), P2 = c(75, 7, NA, 7), Diff = c(60,
-51, NA, NA)), .Names = c("Name", "P1", "P2", "Diff"), class = "data.frame", row.names = c(NA,
-4L))
这是我的代码:
方法1:使用spread
[有效]
data.table::setDT(Test_File)
cutoff<-2013
Test_File[Test_File$Ship_Date>=cutoff,"Ship_Period"]<-"P2"
Test_File[Test_File$Ship_Date<cutoff,"Ship_Period"]<-"P1"
Diff_Table<- Test_File %>%
dplyr::group_by(Ship_Period,Name) %>%
dplyr::mutate(Revenue = sum(Revenue)) %>%
dplyr::select(Ship_Period, Name,Revenue) %>%
dplyr::ungroup() %>%
dplyr::distinct() %>%
tidyr::spread(key = Ship_Period,value = Revenue) %>%
dplyr::mutate(Diff = `P2` - `P1`)
方法2:使用dplyr
[不起作用:在Diff
列中生成NAs。]
Diff_Table<- Test_File %>%
dplyr::group_by(Ship_Period,Name) %>%
dplyr::mutate(Revenue = sum(Revenue)) %>%
dplyr::select(Ship_Period, Name,Revenue) %>%
dplyr::ungroup() %>%
dplyr::distinct() %>%
dplyr::arrange(Name,Ship_Period, Revenue) %>%
dplyr::group_by(Ship_Period,Name) %>%
dplyr::mutate(Diff = diff(Revenue))
方法三:使用 data.table
【无效:会在 Diff
列中生成全零。】
Test_File[,Revenue1 := sum(Revenue),by=c("Ship_Period","Name")]
Diff_Table<-Test_File[,.(Diff = diff(Revenue1)),by=c("Ship_Period","Name")]
问题:请问有人能帮我解决上述的第二种方法和第三种方法吗?我对R语言还比较陌生,如果我的工作听起来太基础,请见谅。我仍在学习这门语言。
Pineapple
的P1
值应该是NA
吗? - jogoNA
-number
=NA
和number
-NA
=NA
。所以,我相信这并不重要。我创建这些条目是为了确保当P1
或P2
中的一个缺失时,代码不会崩溃。这有帮助吗? - watchtower