【发布时间】: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