我正在为数据分析开发R。我有一个Dataframe,用于存储一年中每个月的数据。在特定年份的某些月份中,数据丢失。我当前使用的数据框如下。
如何以以下方式修改数据框中的数据以存储在另一个数据框中?
Year列的类型为yearmon,n列的类型为int。
答案 0 :(得分:1)
使用tidyverse解决方案
library(tidyverse)
##Recreate data
df <- tibble(
Year = c("Dec-13", "Jan-14","Feb-14","Mar-14",
"Apr-14", "May-14","Jun-15","Jul-14",
"Aug-15","Sep-18"),
n = c(1,8,2,4,8,9,2,1,1,1)
)
##convert to character, spread, and fill
df_2 <- df %>%
mutate(Year = parse_character(Year)) %>%
separate(Year, into = c("Month", "Year")) %>%
mutate(Year = paste0("20",Year)) %>%
spread(Year,n, fill = "-") %>%
mutate(Month = factor(Month, levels = c("Dec","Jan","Feb", "Mar","Apr",
"May","Jun","Jul", "Aug",
"Sep"))) %>%
arrange(Month)
df_2