用以前记录和当前值的平均值替换负值
Replace negative values with mean of the previous record and current value
我对一个问题有 3/4 的答案,但在最后一部分需要一些帮助。我有一些公司息税前利润的数据。如果息税前利润为负,我想用上一年和当年的平均值替换该值,例如,如果公司在 1993 年录得负息税前利润,我想得到负年份(1993 年)和前一年 (1992).
我有以下代码(我在 Whosebug How to replace NA with mean by subset in R (impute with plyr?) 上找到的)但我想更改 impute.mean 函数以反映我想要的更改。那就是我真的不想将负数转换为 NA 的
years <- c(1990, 1991, 1992, 1993, 1994)
gvkey <- c(1000, 1100, 1200, 1300, 1400, 1500)
join <- as.data.frame(rep_len(years, length.out = length(gvkey) *
length(years)))
join$gvkey <- rep(gvkey, length(years))
join$ebit <- runif(nrow(join), min=-100, max=100)
join$ebit[join$ebit < 0] <- NA ## very inefficient way of recognizing negative values
colnames(join) <- c("year", "gvkey", "ebit")
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
join <- join %>%
group_by(gvkey) %>%
mutate(
ebit = impute.mean(ebit))
我还发现这个除了 NA 问题之外是理想的 R replacing missing values with the mean of surroundings values
x <- (na.locf(join) + rev(na.locf(rev(join))))/2
这似乎可以解决问题。现在的问题是,如果连续两年都是负值......
y <- join%>%group_by(gvkey)%>%mutate(adj_ebit=purrr::accumulate(ebit,~ifelse(.y<0,(.y+.x)/2,.y)))
我对一个问题有 3/4 的答案,但在最后一部分需要一些帮助。我有一些公司息税前利润的数据。如果息税前利润为负,我想用上一年和当年的平均值替换该值,例如,如果公司在 1993 年录得负息税前利润,我想得到负年份(1993 年)和前一年 (1992).
我有以下代码(我在 Whosebug How to replace NA with mean by subset in R (impute with plyr?) 上找到的)但我想更改 impute.mean 函数以反映我想要的更改。那就是我真的不想将负数转换为 NA 的
years <- c(1990, 1991, 1992, 1993, 1994)
gvkey <- c(1000, 1100, 1200, 1300, 1400, 1500)
join <- as.data.frame(rep_len(years, length.out = length(gvkey) *
length(years)))
join$gvkey <- rep(gvkey, length(years))
join$ebit <- runif(nrow(join), min=-100, max=100)
join$ebit[join$ebit < 0] <- NA ## very inefficient way of recognizing negative values
colnames(join) <- c("year", "gvkey", "ebit")
impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))
join <- join %>%
group_by(gvkey) %>%
mutate(
ebit = impute.mean(ebit))
我还发现这个除了 NA 问题之外是理想的 R replacing missing values with the mean of surroundings values
x <- (na.locf(join) + rev(na.locf(rev(join))))/2
这似乎可以解决问题。现在的问题是,如果连续两年都是负值......
y <- join%>%group_by(gvkey)%>%mutate(adj_ebit=purrr::accumulate(ebit,~ifelse(.y<0,(.y+.x)/2,.y)))