r - 在 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))
解决方案
我们可以用tidyverse
library(dplyr)
library(purrr)
library(lubridate)
df <- df %>%
mutate(Time = ymd(Time))
在数据集列表上
list_df <- map(list_df, ~ .x %>%
mutate(Time = ymd(Time))
推荐阅读
- amazon-web-services - AWS 如何将 VPC 接口终端节点关联到另一个 VPC 中的特定 NLB
- jquery - 检查 Array 中的多个值并在 html 中附加第三个值
- laravel-dusk - Laravel Dusk:迁移和种子测试数据库一次
- docusignapi - 将签名者分配给特定的签名表单字段
- c# - 即使在应用程序关闭后仍附加多个消费者。活动MQ
- r - 为什么/如何一些包在无名环境中定义它们的功能?
- amazon-web-services - 如何监控/监听 aws 服务?
- html - 使用线性渐变将顶部切角移动到底部
- mongodb - AWS EC2 SSH 隧道堡垒服务器
- javascript - 循环遍历数字数组以在纯javascript中构造索引节点的对象