Advertisements
I’m trying to add a new row to a data frame but unable to rbind due to data format. Overall I’m calculating YoY for most recent quarter and want to add row to the same ‘date’ column.
# data
date <- c("2022-12-1","2022-6-1","2022-9-1","2022-1-1","2021-12-1","2021-6-1")
value1 <- c(2605,3804,5932,58923,7877,9999)
value2 <- c(98,45,13,23,77,49)
df <- data.frame(date,value1,value2)
# set to date & order
df$date <- as.Date(df$date, format = "%Y-%m-%d")
df <- df[order(df$date), ]
current_q <- ceiling(length(df$value1)/4)
if (current_q >= 2) {
df$yoy1 <- NA
df$yoy1[current_q] <- 100 * (df$value1[current_q] - df$value1[current_q - 4]) / df$value1[current_q -4]
df$yoy2 <- NA
df$yoy2[current_q] <- 100 * (df$value2[current_q] - df$value2[current_q - 4]) / df$value2[current_q -4]
} else {
df$yoy1 <- NA
}
# trying to add new row here
yoy_row <- data.frame(date = "yoy", value1 = df$yoy1, value2 = df$yoy2)
#remove unwanted column
df <- df[, c("date","value1","value2")]
df <- rbind(df, yoy_row)
YoY is supposed to be calculated for value 1 & 2 to be added as a new row. Is it really a class issue and how can I fix this?
Expected output
date value1 value2
6 2021-06-01 9999 49
5 2021-12-01 7877 77
4 2022-01-01 58923 23
2 2022-06-01 3804 45
3 2022-09-01 5932 13
1 2022-12-01 2605 98
7 YoY -21.2 57.14
>Solution :
# data
date <- c("2022-12-1","2022-6-1","2022-9-1","2022-1-1","2021-12-1","2021-6-1")
value1 <- c(2605,3804,5932,58923,7877,9999)
value2 <- c(98,45,13,23,77,49)
df <- data.frame(date,value1,value2)
# set to date & order
df$date <- as.Date(df$date, format = "%Y-%m-%d")
df <- df[order(df$date), ]
current_q <- ceiling(length(df$value1)/4)
if (current_q >= 2) {
df$yoy1 <- NA
df$yoy1[current_q] <- 100 * (df$value1[current_q] - df$value1[current_q - 4]) / df$value1[current_q -4]
df$yoy2 <- NA
df$yoy2[current_q] <- 100 * (df$value2[current_q] - df$value2[current_q - 4]) / df$value2[current_q -4]
} else {
df$yoy1 <- NA
}
# trying to add new row here
yoy_row <- data.frame(date = "yoy", value1 = df$yoy1, value2 = df$yoy2)
#remove unwanted column
df <- df[, c("date","value1","value2")]
df$date <- as.character(df$date) # convert column to character then subsequent call to `rbind` will succeed
df <- rbind(df, yoy_row)