首页 > 解决方案 > 在 for 循环中集中字符串

问题描述

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

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

标签: rfor-looptidyversestringr

解决方案


我们可以用tidyverse

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

在数据集列表上

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

推荐阅读