【问题标题】:Concentating strings in for Loop在 for 循环中集中字符串
【发布时间】:2021-03-18 10:45:08
【问题描述】:

当我尝试在数据帧列表中连接字符串时遇到了问题。最终目标是遍历一系列嵌套列表(列表 > 列表 > 数据框)并应用一个函数来集中特定列并替换数据框列中的值。

library(purrr)
library(tibble)
library(dplyr)
library(tidyverse)
library(stringr)

Time <- c("20060126000000","20060129000000","20050629000000")
Colvalue2 <- c(5,4,8)
Colvalue1 <- c(22,765,12)

time_list <- list(Time,Colvalue2,Colvalue1)
time_listdf <- as.data.frame(time_list, col.names = c("Time","Colvalue2","Colvalue1"))

# The time is formatted so that the first 1 - 4 Values are the year e.g "2006", the second 5 - 6 are month e.g "01", 
# and the third part from 7 - 8 is the date e.g "26". The final values are the seconds etc (not relevant to this example)

for (i in time_listdf$Time){
  
  year_str <- str_sub(i, 1,4)
  month_string <- str_sub(i, 5,6)
  date_str <- str_sub(i, 7,8)
  final_str <- str_c(date_str, month_string, year_str, sep = '/')
  
}

数据框在嵌套列表中的数据框的每一列中看起来都是这样的。


# Example date value = 26/01/2006

Time_new <- c("26/01/2006","29/01/2006","29/06/2005")
Colvalue2 <- c(5,4,8)
Colvalue1 <- c(22,765,12)

new_df <- as.data.frame(list(Time_new,Colvalue1,Colvalue2))

【问题讨论】:

    标签: r for-loop tidyverse stringr


    【解决方案1】:

    如果您将Time 列替换为您可以使用as.Date 执行的实际日期会更好。

    time_listdf$Time <- as.Date(time_listdf$Time, '%Y%m%d')
    time_listdf
    
    #        Time Colvalue2 Colvalue1
    #1 2006-01-26         5        22
    #2 2006-01-29         4       765
    #3 2005-06-29         8        12
    

    如果您想以特定格式显示日期,您可以使用format。


    要将此应用于数据框列表,请使用lapply,如果您的列表称为list_df,您可以这样做:

    list_df <- lapply(list_df, function(x) 
                      transform(x, Time = as.Date(Time, '%Y%m%d')))
    

    【讨论】:

      【解决方案2】:

      我们可以使用tidyverse

      library(dplyr)
      library(purrr)
      library(lubridate)
      df <- df %>%
            mutate(Time = ymd(Time))
      

      在数据集列表上

      list_df <- map(list_df, ~ .x %>%
                                   mutate(Time = ymd(Time))
      

      【讨论】:

        猜你喜欢
        • 2020-01-22
        • 1970-01-01
        • 1970-01-01
        • 2015-12-16
        • 2023-03-15
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多