【发布时间】:2016-04-12 04:52:53
【问题描述】:
继续这个问题:Add row in R dataframe by unique factor in column showing percent change by Month
testing <- data.frame(
MONTH = c("MTD: 12", "MTD: 12", "MTD: 11", "MTD: 12", "MTD: 12", "MTD: 12"),
YEAR = c(2012, 2013, 2014, 2015, 2013, 2014),
Client = c("A.", "A.", "A.", "B.", "B.", "B."),
Revenue = c(320, 205, 166L, 152, 150, 138),
Col1 = c(651, 485, 533, 3932, 171, 436),
Col2 = c(478, 335, 305, 238, 115, 251),
Col3 = c(73, 69, 57, 6, 67, 57),
Col4 = c(6.7, 6.1, 5.5, 6.4, 13.1, 5.5)
)
# subset just the month=12 rows
test12 <- testing[testing$MONTH=="MTD: 12", ]
test12 <- test12[order(test12$Client, test12$YEAR), ]
# define a function to calculate percent change
pctchange <- function(x) {
L <- length(x)
c(NA, 100 * (x[-1] - x[-L]) / x[-L])
}
# calculate percent change for all columns, by client
change <- apply(test12[, c("Revenue", "Col1", "Col2", "Col3", "Col4")], 2,
function(y) unlist(tapply(y, test12$Client, pctchange)))
change <- data.frame(change)
names(change) <- paste0("d", names(change))
test12b <- cbind(test12[, c("MONTH", "YEAR", "Client")], change)
# merge back with monthly data
merge(testing, test12b, all=TRUE)
因此,在运行此代码后,您会得到一个已被客户端拆分的列表。
我想运行以下代码,如果该因素(客户端)的行数大于 2,则该代码实际上将删除第二行。
我已经试过了,但是没有用:
testing<-ifelse(length(splitresult)>2,splitresult[-2,],splitresult)
所有这些的最终目标:
1) 只获取上一年与上一年的百分比变化,而不显示上一年的 NA 等中间数据。但是,如果它是一个新客户,我确实希望那里的 NA 指定它是一个新客户。所以这就是为什么我尝试了上面没有工作的代码。
2) 我想在 MTD: 12 2014 中按收入拆分的客户重新排序。
splitlist[order(sapply(splitlist, function(x) (x[["Revenue"]])))]
(不起作用:假设 splitlist 是列表的名称)
如果有人可以帮助我解决这两个问题,那将非常有帮助。谢谢!
【问题讨论】:
-
您是否尝试过使用
dplyr包? -
我没有。我认为我需要在问题的第二部分使用 sapply,但不确定如何处理所涉及的月份/年份。我已经编辑了这个问题,向您展示我尝试过的@Jubbles
标签: r split reorderlist