AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-12836787

tassones's questions

Martin Hope
tassones
Asked: 2025-04-29 01:34:56 +0800 CST

如何格式化 facet_wrap 图的标题以匹配面条样式?

  • 8

我正在尝试将绘图标题的格式设置facet_wrap为与构面条带的样式一致。在下面的绘图中,我添加了标题“len”,但它的格式看起来与右侧构面条带(例如 0.5、1、2)的格式不同。如何使标题看起来像构面条带(例如,灰色矩形框、黑色轮廓、文本沿绘图宽度居中等)?

library(tidyverse)

ToothGrowth |> 
  ggplot(aes(x = dose, y = len)) + 
  geom_boxplot(aes(fill = supp)) +
  labs(title = 'len',
       y = NULL) +
  theme_bw() +
  facet_wrap(~dose, ncol = 1, strip.position = "right")

创建于 2025-04-28,使用reprex v2.1.1

  • 2 个回答
  • 36 Views
Martin Hope
tassones
Asked: 2024-12-31 05:21:19 +0800 CST

如何使图例颜色条与我的面包裹绘图面板的高度相同?

  • 6

使用时,如何调整图例颜色栏高度以匹配图的高度facet_wrap()?此相关 SO 问题为单个图提供了一个很好的解决方案,但当存在多个图时,颜色栏会延伸到构面换行标题和轴文本的一半。我希望颜色栏仅从构面换行标题的底部延伸到轴文本的顶部。

制作基图

(注意小彩条的高度)

library(tidyverse)
library(ggcorrplot)
library(reshape2)

iris %>%
  group_by(Species) %>%
  summarise(correlation = list(cor(across(where(is.numeric))))) %>%
  ungroup() %>%
  mutate(correlation_df = map(correlation, ~ melt(.x, varnames = c("Var1", "Var2")))) %>%
  select(Species, correlation_df) %>%
  unnest(correlation_df) %>%
  ggplot(aes(x = Var1, y = Var2, fill = value)) +
  geom_tile() +
  scale_fill_gradient2(limit = c(-1, 1)) +
  labs(x = NULL,
       y = NULL,
       fill = NULL) +
  theme_bw() +
  facet_wrap(~Species)

使用类似问题的答案

(请注意颜色条延伸到标题和轴文本区域)


make_fullsize <- function() structure("", class = "fullsizebar")

ggplot_add.fullsizebar <- function(obj, g, name = "fullsizebar") {
  h <- ggplotGrob(g)$heights
  panel <- which(grid::unitType(h) == "null")
  panel_height <- unit(1, "npc") - sum(h[-panel])
  
  g + 
    guides(fill = guide_colorbar(barheight = panel_height,
                                 title.position = "right")) +
    theme(legend.title = element_text(angle = -90, hjust = 0.5))
}

iris %>%
  group_by(Species) %>%
  summarise(correlation = list(cor(across(where(is.numeric))))) %>%
  ungroup() %>%
  mutate(correlation_df = map(correlation, ~ melt(.x, varnames = c("Var1", "Var2")))) %>%
  select(Species, correlation_df) %>%
  unnest(correlation_df) %>%
  ggplot(aes(x = Var1, y = Var2, fill = value)) +
  geom_tile() +
  scale_fill_gradient2(limit = c(-1, 1)) +
  labs(x = NULL,
       y = NULL,
       fill = NULL) +
  theme_bw() +
  coord_cartesian(expand = FALSE) +
  make_fullsize() +
  facet_wrap(~Species)

创建于 2024-12-30,使用reprex v2.1.1

我尝试过改变例如的值panel_height,panel_height <- unit(0.95...这提供了一个接近但不精确的答案。当将图放大/缩小时,这个答案也无法很好地扩展。

  • 1 个回答
  • 26 Views
Martin Hope
tassones
Asked: 2024-11-18 22:46:15 +0800 CST

使用大于或等于符号时 facet_wrap 解析错误

  • 7

我正在尝试更改使用 制作的两个图的标题facet_wrap(),其中一个图具有大于或等于符号 ( >=)。我可以让图解析标题,但只要我将 >= 符号放在括号中,标题就会解析失败。当 >= 符号在括号中时,如何让标题进行解析?

library(tidyverse)

mtcars %>% 
  mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
         size = factor(size, levels = c("greater", "lesser"),
                       labels = c("Horsepower >= 100", "Horsepower < 100"))) %>% 
  ggplot(aes(x = mpg, y = wt)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~size, labeller = label_parsed)

当将 >= 放在括号中时,解析失败。


mtcars %>% 
  mutate(size = ifelse(hp >= 100, 'greater', 'lesser'),
         size = factor(size, levels = c("greater", "lesser"),
                       labels = c("Horsepower (>= 100)", "Horsepower (< 100)"))) %>% 
  ggplot(aes(x = mpg, y = wt)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~size, labeller = label_parsed)
#> Error in parse(text = as.character(values)): <text>:1:13: unexpected '>='
#> 1: Horsepower (>=
#>                 ^

创建于 2024-11-18,使用reprex v2.1.1

  • 2 个回答
  • 45 Views
Martin Hope
tassones
Asked: 2024-11-14 05:11:41 +0800 CST

让图例显示填充颜色,并且让 geom_points 带有黑色轮廓

  • 5

在下图中,我希望图例显示变量“颜色”的填充颜色。我还希望图中的所有点都有黑色轮廓。似乎我可以做其中之一,但不能同时做两者(即图例有颜色,点有黑色轮廓)。我选择了有黑色轮廓的形状,如“剪切”图例中所示。

类似的问题:

  • geom_point 周围的黑色轮廓和颜色匹配图例 - ggplot
  • ggplot 点有颜色,但图例(指南)点全是黑色

点周围保留黑色轮廓,但图例全是黑色

library(tidyverse)

diamonds %>% 
  slice(1:20) %>% 
  ggplot(aes(x = x,
             y = y,
             shape = cut,
             fill = color)) +
  geom_point(size = 3,
             alpha = 0.8) +
  scale_shape_manual(values = c('Ideal' = 21,
                                'Premium' = 22,
                                'Good' = 23,
                                'Very Good' = 24,
                                'Fair' = 25)) +
  scale_fill_manual(values = c('E' = '#ca0020',
                               'F' = '#f4a582',
                               'H' = '#ffffbf',
                               'I' = '#92c5de',
                               'J' = '#0571b0')) +
  theme_bw()

删除点周围的黑色轮廓,但图例全是彩色

diamonds %>% 
  slice(1:20) %>% 
  ggplot(aes(x = x,
             y = y,
             shape = cut,
             fill = color,
             color = color)) +
  geom_point(size = 3,
             alpha = 0.8) +
  scale_shape_manual(values = c('Ideal' = 21,
                                'Premium' = 22,
                                'Good' = 23,
                                'Very Good' = 24,
                                'Fair' = 25)) +
  scale_fill_manual(values = c('E' = '#ca0020',
                               'F' = '#f4a582',
                               'H' = '#ffffbf',
                               'I' = '#92c5de',
                               'J' = '#0571b0')) +
  scale_color_manual(values = c('E' = '#ca0020',
                                'F' = '#f4a582',
                                'H' = '#ffffbf',
                                'I' = '#92c5de',
                                'J' = '#0571b0')) +
  theme_bw()

编辑:我知道我可以添加第二组稍微大一点的点来获得解决方法,但这太草率了

diamonds %>% 
  slice(1:20) %>% 
  ggplot(aes(x = x,
             y = y,
             shape = cut,
             fill = color,
             color = color)) +
  geom_point(size = 3.5,
             alpha = 0.5,
             color = 'black') +
  geom_point(size = 3,
             alpha = 0.8) +
  scale_shape_manual(values = c('Ideal' = 21,
                                'Premium' = 22,
                                'Good' = 23,
                                'Very Good' = 24,
                                'Fair' = 25)) +
  scale_fill_manual(values = c('E' = '#ca0020',
                               'F' = '#f4a582',
                               'H' = '#ffffbf',
                               'I' = '#92c5de',
                               'J' = '#0571b0')) +
  scale_color_manual(values = c('E' = '#ca0020',
                                'F' = '#f4a582',
                                'H' = '#ffffbf',
                                'I' = '#92c5de',
                                'J' = '#0571b0')) +
  theme_bw()

创建于 2024-11-13,使用reprex v2.1.1

  • 2 个回答
  • 42 Views
Martin Hope
tassones
Asked: 2024-04-23 23:10:41 +0800 CST

使用 ggcorrplot 相关矩阵上的上标和下标标签

  • 8

我正在尝试自定义使用该包制作的相关矩阵上的标签ggcorrplot。但是,我无法使上标或下标格式正常工作。如何在不使用 Unicode 字符的情况下使标签正确显示?

library(tidyverse)
library(ggcorrplot)

# Example Data
M <- cor(mtcars)[1:3,1:3]

# Attempt 1: Not formatted correctly
colnames(M) <- c("Temperature\n (^o C)", "PO[4]^2", "Oxygen\n (mg L^-1)")
rownames(M) <- c("Temperature\n (^o C)", "PO[4]^2", "Oxygen\n (mg L^-1)")

ggcorrplot(M,
           type = "lower",
           lab = TRUE,
           ggtheme = theme_bw())


# Attempt 2: Produces error message
ggcorrplot(M,
           type = "lower",
           lab = TRUE,
           scale_x_discrete(labels = c("mpg" = expression(Temperature~(degree*C)),
                                       "cyl" = expression(PO[4]^2),
                                       "disp" = expression(Oxygen~(mg~L^-1)))),
           scale_y_discrete(labels = c("mpg" = expression(Temperature~(degree*C)),
                                       "cyl" = expression(PO[4]^2),
                                       "disp" = expression(Oxygen~(mg~L^-1)))),
           ggtheme = theme_bw())
#> Error in match.arg(method): 'arg' must be NULL or a character vector

创建于 2024-04-23,使用reprex v2.1.0

  • 2 个回答
  • 23 Views
Martin Hope
tassones
Asked: 2024-04-20 04:53:13 +0800 CST

删除facet_wrap标签之间的水平线

  • 6

我正在用来ggplot制作一个三面板人物。我想facet_wrap按州并在标签中包含城市名称,但是,当我这样做时,州和城市名称之间会出现一条水平线。如何去掉水平线?

library(tidyverse)

set.seed(333)

# Example dataset
df <- data.frame(
  state = c("North Carolina","North Carolina","North Carolina",
            "North Carolina","North Carolina","North Carolina",
            "Virginia","Virginia","Virginia"),
  city = c("Boone","Boone","Boone",
           "Elizabeth City","Elizabeth City","Elizabeth City",
           "Norfolk","Norfolk","Norfolk"),
  year = rep(seq(2000,2004,2),3),
  value = round(rnorm(9,100,50))
)

# Example plot (how can I remove the horizontal line between the state and city labels?)
df %>%
  ggplot(aes(x = year, y = value)) +
  geom_point() +
  theme_bw() +
  facet_wrap(~state+city)

创建于 2024-04-19,使用reprex v2.1.0

  • 2 个回答
  • 32 Views
Martin Hope
tassones
Asked: 2024-04-05 03:52:08 +0800 CST

ggplot2:当日期是一个因素时,使点与实际日期对齐

  • 5

我制作了一个具有不连续 x 轴的时间序列,但是,我只知道当 x 轴是一个因素时如何制作此类图Date。这导致的问题是,图中的点与表明这些点是在当月第一天收集的因素一致,但事实并非如此。有什么方法可以使点与实际对齐,Date同时保持 x 轴不连续?

例子

library(tidyverse)
library(grid)

set.seed(333)

# Create example dataset
df <- data.frame(
  Group = c('A','A','A','A','A','A','B','B','B','B','B','B'),
  Date = rep(c('2021-07-13','2021-08-22','2021-09-04','2022-06-20','2022-07-08','2022-08-25'), 2),
  Value = round(rnorm(12,50,20)))

# Do some data wrangling
df <- df %>%
  mutate(Date = as.Date(Date),
         year = year(Date),
         mon = month(Date),
         mon_abb = month.abb[mon],
         monYear = paste(mon_abb,year, sep = ' ')) %>%
  select(!c(mon,year,mon_abb))

# Will need the month abbreviation
sample_dates <- unique(df$monYear)

# Make figure
# Note: the points align on the month but I would like them to
# align with the actual calendar Date (i.e., all points would move
# to the right because none were collected on the 1st of the month)
ggplot(data = df, aes(x = factor(Date), y = Value, group = Group)) +
  geom_point(aes(fill = Group), size = 3, shape = 21, color = "black") +
  scale_x_discrete(labels = substr(sample_dates, 1, 3)) + # Pulls the month abb. for x-axis label
  xlab("") +
  theme_bw() +
  theme(plot.margin = unit(c(1, 1, 2, 1), "lines"),
        axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1),
        legend.position = 'right',
        panel.border = element_blank()) +
  guides(fill = guide_legend(nrow = 2)) +
  coord_cartesian(clip = 'off', ylim = c(0, 100)) +
  annotation_custom(rectGrob(gp = gpar(fill = NA))) +
  annotate(geom = "text", x = 2, y = -16, label = 2021, size = 4.5) +
  annotate(geom = "text", x = 5, y = -16, label = 2022, size = 4.5) +
  annotate(geom = 'rect', xmin = 3.4, xmax = 3.6, ymin = -10, ymax = -3, fill = 'white') +
  annotate(geom = 'segment', x = c(3.4,3.6), xend = c(3.4,3.6), y = -8, yend = -3)

创建于 2024-04-04,使用reprex v2.0.2

  • 1 个回答
  • 28 Views
Martin Hope
tassones
Asked: 2024-01-17 03:58:22 +0800 CST

如果时间缺失,如何将时间添加到日期时间列

  • 6

我有一个数据框,其中的日期时间列以 4 小时为间隔。当时间部分应该是00:00:00(小时:分钟:秒)时,日期中缺少时间。当时间缺失时如何添加00:00:00日期?

示例数据

dat <- data.frame(
  dateTime = c('2016-07-01',
               '2016-07-01 04:00:00',
               '2016-07-01 08:00:00',
               '2016-07-01 12:00:00',
               '2016-07-01 16:00:00',
               '2016-07-01 20:00:00',
               '2016-07-02')
)

str(dat)
#> 'data.frame':    7 obs. of  1 variable:
#>  $ dateTime: chr  "2016-07-01" "2016-07-01 04:00:00" "2016-07-01 08:00:00" "2016-07-01 12:00:00" ...

dat
#>              dateTime
#> 1          2016-07-01
#> 2 2016-07-01 04:00:00
#> 3 2016-07-01 08:00:00
#> 4 2016-07-01 12:00:00
#> 5 2016-07-01 16:00:00
#> 6 2016-07-01 20:00:00
#> 7          2016-07-02

不过,我可以在下面使用它,我的真实数据集缺少行,所以我正在寻找一种替代方案,可以00:00:00在没有时间时添加。

library(tidyverse)

dat <- dat %>%
  mutate(dateTime_cor = seq(from = as.POSIXct("2016-07-01 00:00:00"),
                            to = as.POSIXct("2016-07-02 00:00:00"),
                            by = "4 hours")) %>%
  select(-dateTime)

str(dat)
#> 'data.frame':    7 obs. of  1 variable:
#>  $ dateTime_cor: POSIXct, format: "2016-07-01 00:00:00" "2016-07-01 04:00:00" ...

dat
#>          dateTime_cor
#> 1 2016-07-01 00:00:00
#> 2 2016-07-01 04:00:00
#> 3 2016-07-01 08:00:00
#> 4 2016-07-01 12:00:00
#> 5 2016-07-01 16:00:00
#> 6 2016-07-01 20:00:00
#> 7 2016-07-02 00:00:00

创建于 2024-01-16,使用reprex v2.0.2

  • 1 个回答
  • 22 Views
Martin Hope
tassones
Asked: 2023-12-14 00:59:22 +0800 CST

在散点图变量名称中允许空格 R闪亮

  • 5

我正在 Rstudio 中开发一个闪亮的应用程序。该应用程序创建两个图 - 时间序列和散点图。绘制的变量是Water Temperature和Air Temperature。时间序列图可以毫无问题地处理变量名称中的空格,但是,与变量名称关联的散点图出现错误。

错误是:

Warning: Error in parse: <text>:1:7: unexpected symbol
1: Water Temperature
          ^

或者

Warning: Error in parse: <text>:1:5: unexpected symbol
1: Air Temperature
        ^

我怀疑这些错误与水/空气和温度之间的空间有关。保留空格而不是用下划线或其他空格填充符替换它至关重要。制作散点图时如何保持变量名称中的空格?

library(tidyverse)
library(shiny)
library(shinydashboard)

# Create example dataset
set.seed(123)

dat <- data.frame(
  Time = rep(seq(1,10,1), times = 2),
  Site = rep(c('A', 'B'), each = 10),
  Water_Temperature = round(rnorm(20, mean = 20, sd = 5)),
  Air_Temperature = round(rnorm(20, mean = 25, sd = 3))
)

dat <- dat %>%
  rename(`Water Temperature` = Water_Temperature,
         `Air Temperature` = Air_Temperature)

dat_long <- dat %>%
  pivot_longer(cols = c("Water Temperature","Air Temperature"),
               names_to = 'Variable',
               values_to = 'Value') %>%
  arrange(Site, Time)

# Define user interface for time series and scatterplot
ui.R <- dashboardPage(
  dashboardHeader(title = "Example", titleWidth = 350),
  dashboardSidebar(
    tags$head(
      tags$style(
        HTML("
          .sidebar-footer {
            text-align: center;
          }
          .sidebar-logo {
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .sidebar-menu a span {
            font-size: 24px;
          }
        ")
      )
    ),
    sidebarMenu(
      menuItem("Time Series", tabName = "time_series", icon = icon("chart-line")),
      menuItem("Scatterplot", tabName = "scatter_plot", icon = icon("chart-line"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "time_series",
        fluidRow(
          box(
            title = "Time Series",
            status = "primary",
            solidHeader = TRUE,
            width = 2,
            selectInput("siteInput", "Select Site", choices = unique(dat_long$Site)),
            selectInput("variableInput", "Select Variable", choices = unique(dat_long$Variable))
          ),
          box(
            title = "Plot",
            status = "primary",
            solidHeader = TRUE,
            width = 10,
            plotOutput("timeSeriesPlot", height = "700px")
          )
        )
      ),
      tabItem(
        tabName = "scatter_plot",
        fluidRow(
          box(
            title = "Scatterplot",
            status = "primary",
            solidHeader = TRUE,
            width = 2,
            selectInput("siteInput2", "Select Site", choices = unique(dat_long$Site)),
            selectInput("xAxisInput", "Select X-axis Variable:", choices = unique(dat_long$Variable)),
            selectInput("yAxisInput", "Select Y-axis Variable:", choices = unique(dat_long$Variable))
          ),
          box(
            title = "Plot",
            status = "primary",
            solidHeader = TRUE,
            width = 10,
            plotOutput("scatterPlot", height = "700px")
          )
        )
      ),
      tabItem(
        tabName = "site_info",
        fluidPage(
          fluidRow(
            selectInput("siteInput3", "Select Site", choices = unique(dat_long$Site)),
            column(4, dataTableOutput('table'))
          )
        )
      )
    )
  )
)

# Define server
server.R <- function(input, output) {
  output$timeSeriesPlot <- renderPlot({
    filteredData <- dat_long %>%
      filter(Site == input$siteInput, Variable == input$variableInput)
    
    variableName <- unique(filteredData$Variable)
    yLabel <- ifelse(variableName == "Water Temperature", expression(Water~Temperature~(degree*C)),
                     ifelse(variableName == "Air Temperature", expression(Air~Temperature~(degree*C))))
    
    ggplot(filteredData, aes(x = Time, y = Value)) +
      geom_line() +
      geom_point() +
      scale_x_continuous(breaks = seq(1,10,1)) +
      labs(x = "", y = yLabel,
           title = paste('Site:', input$siteInput)) +
      theme_bw()
  })
  
  output$scatterPlot <- renderPlot({
    filteredData2 <- dat_long %>%
      filter(Site == input$siteInput2)
    
    # Create a reactive label to display the units for the selected variable on the x and y axes
    xLabel <- reactive({
      switch(input$xAxisInput[1],
             `Air Temperature` = expression(Air~Temperature~(degree*C)),
             `Water Temperature` = expression(Water~Temperature~(degree*C)))
    })
    
    yLabel <- reactive({
      switch(input$yAxisInput[1],
             `Air Temperature` = expression(Air~Temperature~(degree*C)),
             `Water Temperature` = expression(Water~Temperature~(degree*C)))
    })
    
    ggplot(filteredData2, aes_string(x = input$xAxisInput, y = input$yAxisInput)) +
      geom_point() +
      labs(x = xLabel(), y = yLabel(),
           title = paste('Site:', input$siteInput2)) +
      theme_bw()
  })
}

# Run the application
shinyApp(ui = ui.R, server = server.R)

时间序列图有效 在此输入图像描述 散点图无效 在此输入图像描述

  • 1 个回答
  • 11 Views
Martin Hope
tassones
Asked: 2023-09-27 01:44:13 +0800 CST

Shiny App:散点图对多个输入做出反应

  • 5

我正在尝试制作一个闪亮的应用程序,允许用户为散点图的 x 轴和 y 轴选择一个组 ( cut) 和一个变量(即depth、table或)。price下面的 UI 代码可以很好地允许用户进行选择,但是,我在服务器方面遇到了问题。我认为问题在于将 UI 选择过滤到两个数据框中,然后使用rbind()它们来组合它们,但我不知道另一种继续进行的方法。

如何对ggplot()用户对 x 轴和 y 轴的两个选择做出反应?

例子:

library(shiny)
library(tidyverse)

dat <- diamonds %>%
  select(cut,depth,table,price) %>%
  pivot_longer(cols = c('depth','table','price'),
               names_to = 'Variable',
               values_to = 'Value')

ui <- fluidPage(
  selectInput("x_cut", "X-axis Cut", choices = unique(dat$cut)),
  selectInput("x_variable", "X-axis Variable", choices = unique(dat$Variable)),
  selectInput("y_cut", "Y-axis Cut", choices = unique(dat$cut)),
  selectInput("y_variable", "Y-axis Variable", choices = unique(dat$Variable)),
  plotOutput("plot")
)

server <- function(input, output) {
  output$plot <- renderPlot({
    filtered_xdat <- dat %>%
      filter(cut == input$x_cut, Variable == input$x_variable)
    
    filtered_ydat <- dat %>%
      filter(cut == input$y_cut, Variable == input$y_variable)
    
    filtered_dat <- rbind(filtered_xdat, filtered_ydat)
      
    filtered_dat %>%
      ggplot() +
      geom_point(aes(x = input$x_variable,
                     y = input$y_variable)) +
      geom_point()
  })
}

shinyApp(ui, server)

# Warning: Error in geom_point: Problem while setting up geom.
# ℹ Error occurred in the 2nd layer.
# Caused by error in `compute_geom_1()`:
#   ! `geom_point()` requires the following missing aesthetics: x and y

我已经尝试过这个:

server <- function(input, output) {
  output$plot <- renderPlot({

    filtered_xdat <- dat %>%
      filter(cut == input$x_cut,
             xVariable == input$x_variable) %>%
      as.data.frame()

    filtered_ydat <- dat %>%
      filter(cut == input$y_cut,
             yVariable == input$y_variable) %>%
      as.data.frame()

    ggplot() +
      geom_point(aes(x = filtered_xdat$xVariable, y = filtered_ydat$yVariable)) +
      theme_minimal()
  })
}

# Warning: Error in filter: ℹ In argument: `xVariable == input$x_variable`.
# Caused by error:
#   ! object 'xVariable' not found

还有这个:

server <- function(input, output) {
  output$plot <- renderPlot({

    filtered_dat <- dat %>%
      filter(cut %in% c(input$x_cut, input$y_cut),
             Variable %in% c(input$x_variable, input$y_variable))
    
    ggplot(data = filtered_dat, aes(x = !!sym(input$x_variable), y = !!sym(input$y_variable))) +
      geom_point() +
      theme_minimal()
  })
}

# Warning: Error in geom_point: Problem while computing aesthetics.
# ℹ Error occurred in the 1st layer.
# Caused by error in `FUN()`:
#   ! object 'depth' not found
  • 1 个回答
  • 28 Views
Martin Hope
tassones
Asked: 2023-09-06 03:54:02 +0800 CST

将 yy.mmd(d) 日期格式转换为 R 中的 yyyy-mm-dd

  • 7

我正在使用旧的日期格式,其中前两位数字代表 20 世纪的年份。前两位小数是月份(即 01-12),第三位和第四位小数是该月中的日期(即 01-31)。问题在于以零结尾的日期(即 10、20、30)会删除尾随零,因此某些日期格式仅具有三位小数。

如何恢复尾随零,以便可以将此旧日期格式转换为现代日期格式(即 yyyy-mm-dd)?

例子:

library(tidyverse)

# Example data

xx <- data.frame(yr_mo_da = c('89.1208','89.1209','89.121', '89.1211'))

# My attempt to extract year, month, day from the old date format
# NOTE how the day is not extracted properly because there is not a fourth decimal place on Dec. 10

xx$year <- as.numeric(gsub("\\..*","",xx$yr_mo_da))
xx$month <- as.numeric(sub("^[0-9]+\\.([0-9]{2}).*", "\\1", xx$yr_mo_da))
xx$day <- as.numeric(sub("^[0-9]+\\.[0-9]{2}([0-9]{2}).*", "\\1", xx$yr_mo_da))
xx
#>   yr_mo_da year month    day
#> 1  89.1208   89    12  8.000
#> 2  89.1209   89    12  9.000
#> 3   89.121   89    12 89.121
#> 4  89.1211   89    12 11.000

# Create modern date format

xx <- xx %>%
  mutate(year = year + 1900,
         Date = make_date(year,month,day)) %>%
  select(-c(yr_mo_da,year,day,month))
xx
#>         Date
#> 1 1989-12-08
#> 2 1989-12-09
#> 3       <NA>
#> 4 1989-12-11

正确的输出应该如下所示:

xx
#>         Date
#> 1 1989-12-08
#> 2 1989-12-09
#> 3 1989-12-10
#> 4 1989-12-11

创建于 2023-09-05,使用reprex v2.0.2

  • 2 个回答
  • 30 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve