gpt4 book ai didi

r - 根据新列扩展数据框

转载 作者:行者123 更新时间:2023-12-04 11:04:11 25 4
gpt4 key购买 nike

我有以下数据框:

df <- data.frame(
month=c("July", "August", "August"),
day=c(31, 1, 2),
time=c(12, 12, 12))

month day time
1 July 31 12
2 August 1 12
3 August 2 12

我有一个时间文本文件(十进制格式),我想用文本文件中的所有时间替换“时间”列。文本文件中有多个日期,每个日期超过 300 条记录。

7-31-2016 #the days are all concatenated together, this line represents the beginning of one day (July 31)
13.12344
13.66445
13.76892
...
8-1-2016 #here is another day (August 1)
14.50333
14.52000
14.53639
...

但是,文本文件比当前数据帧长得多——它有 393 条记录。所以我希望生成的数据框看起来像这样:

    month   day       time
5 July 31 13.12344
6 July 31 13.66445
7 July 31 13.76892
.....
393 August 1 14.50333
394 August 1 14.52000
394 August 1 14.53639

基本上我只需要能够扩展我当前的数据框以匹配新文件中的记录数,同时保持同一天。希望这是有道理的。

最佳答案

# Create txt data
txt <- data.frame(x = c('7-31-2016', '13.12344', '13.66445', '13.76892', '8-1-2016', '14.50333', '14.52000', '14.53639'))
# Load Your data
df <- data.frame(
month=c("July", "August", "August"),
day=c(31, 1, 2),
time=c(12, 12, 12))

# Need a year to join dates
df$year <- 2016

# Create date column
df$date <- as.Date(paste0(df$month, "/", df$day, "/", df$year), format = "%B/%d/%Y")

# Find values with dashes, then replaces with /
txt$dash <- grepl('-', txt$x)
txt$x <- gsub("-", "/", txt$x)

# Adds new columns
library(dplyr)
txt <- mutate(txt, date = ifelse(dash==TRUE, as.Date(x, format = "%m/%d/%Y"), NA))
txt <- mutate(txt, time = ifelse(dash==FALSE, as.numeric(x), NA))

# Fill down values
library(zoo)
txt$date <- na.locf(txt$date)

# Removes NA and keeps necessary columns
txt <- txt[!is.na(txt$time),]
txt <- txt[c("date", "time")]

# Merge
output <- merge(df, txt, by = "date")

关于r - 根据新列扩展数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44523682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com