R语言 如何添加新的行到数据框w/不同的类?

rxztt3cl  于 2023-05-26  发布在  其他
关注(0)|答案(1)|浏览(161)

我尝试向数据框添加新行,但由于数据格式问题无法进行rbind。总的来说,我正在计算最近一个季度的同比数据,并希望将行添加到同一个“日期”列。

# 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应该是计算值1和2作为新行添加。这真的是一个类问题吗?我该如何解决这个问题?
预期产量

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
velaa5lx

velaa5lx1#

# 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)

相关问题