更改 tibble 柱基 R 方法上的 tzone

问题描述 投票:0回答:1

我可以使用 lubridate 语法非常轻松地更改日期时间列的时区,请参阅下面的 df。

但是当我尝试在匿名函数中使用

lapply
attr(x, "tzone) <- ""
来使用基本 R 方法(reprex 中的 df2)时,它只是为每个变量分配一个空字符串。

我通常会使用 lubridate,因为它更容易,但尝试为包开发一个函数并减少对依赖项的依赖,但找不到处理此特定问题的任何地方。我确信我看了这么久,错过了一些简单的东西。

谢谢

library(tidyverse)

df <- tibble::tribble(
  ~DTSTART.TZID.Europe.London, ~DTEND.TZID.Pacific.Auckland, 
  "2023-04-06 12:00:00",       "2023-04-06 20:00:00",   
  "2023-04-06 14:00:00",       "2023-04-06 22:00:00"
)

df %>% 
  mutate(
    DTSTART.TZID.Europe.London = as.POSIXct(DTSTART.TZID.Europe.London, tz = "Europe/London"),
    DTEND.TZID.Pacific.Auckland = as.POSIXct(DTEND.TZID.Pacific.Auckland, tz = "Pacific/Auckland"),
    DTEND.TZID.Pacific.Auckland = lubridate::with_tz(DTEND.TZID.Pacific.Auckland, tzone = "")
  )
#> # A tibble: 2 × 2
#>   DTSTART.TZID.Europe.London DTEND.TZID.Pacific.Auckland
#>   <dttm>                     <dttm>                     
#> 1 2023-04-06 12:00:00        2023-04-06 09:00:00        
#> 2 2023-04-06 14:00:00        2023-04-06 11:00:00

df2 <- df %>% 
  mutate(
    DTSTART.TZID.Europe.London = as.POSIXct(DTSTART.TZID.Europe.London, tz = "Europe/London"),
    DTEND.TZID.Pacific.Auckland = as.POSIXct(DTEND.TZID.Pacific.Auckland, tz = "Pacific/Auckland")
  )
  
  
lapply(df2["DTEND.TZID.Pacific.Auckland"], function(x) {attr(x, "tzone") <- ""})
#> $DTEND.TZID.Pacific.Auckland
#> [1] ""

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

r
1个回答
0
投票

我认为问题在于函数 attr(x, "tzone") 的方式 <- "" is used inside lapply. The function correctly changes the timezone attribute, but it doesn't return the modified datetime object. Instead, it returns the result of the assignment operation, which is "".

要使用基本 R 方法有效更改日期时间列的时区,您需要确保 lapply 中的函数返回修改后的日期时间对象。这可能有效:

# Load necessary library
library(tibble)
library(dplyr)

# Create the initial dataframe
df <- tibble::tribble(
  ~DTSTART.TZID.Europe.London, ~DTEND.TZID.Pacific.Auckland, 
  "2023-04-06 12:00:00",       "2023-04-06 20:00:00",   
  "2023-04-06 14:00:00",       "2023-04-06 22:00:00"
)

# Convert strings to POSIXct with specified timezones
df2 <- df %>% 
  mutate(
    DTSTART.TZID.Europe.London = as.POSIXct(DTSTART.TZID.Europe.London, tz = "Europe/London"),
    DTEND.TZID.Pacific.Auckland = as.POSIXct(DTEND.TZID.Pacific.Auckland, tz = "Pacific/Auckland")
  )

# Correctly modify the timezone using base R
df2$DTEND.TZID.Pacific.Auckland <- lapply(df2["DTEND.TZID.Pacific.Auckland"], function(x) {
  attr(x, "tzone") <- "UTC"
  x
})

df2
© www.soinside.com 2019 - 2024. All rights reserved.