假設我有這個資料框
time1 weight
<chr> <dbl>
1 2012-04-25 17:40:00 82
2 2012-04-25 18:40:00 81
我現在有另一個形式的資料框:
time2 d1 d2 d3
<chr> <dbl> <dbl> <dbl>
1 2012-04-25 17:45:00 1 0 1
我現在想加入這些資料框。d1 d2 d3但是,如果time2大于,我只想使用原始值time1。否則,值應為零。那就是我想要的:
time1 weight d1 d2 d3
<chr> <dbl> <dbl> <dbl> <dbl>
1 2012-04-25 17:40:00 82 0 0 0
2 2012-04-25 18:40:00 81 1 0 1
這樣做的偷偷摸摸的方法是什么?
uj5u.com熱心網友回復:
您可以使用fuzzy-join:
library(fuzzyjoin)
fuzzy_left_join(df1, df2, by = c("time1" = "time2"), match_fun = `>`)
# time1 weight time2 d1 d2 d3
# 1 2012-04-25 17:40:00 82 <NA> NA NA NA
# 2 2012-04-25 18:40:00 81 2012-04-25 17:45:00 1 0 1
不匹配的行用 填充NA。許多函式可以替換NA為其他值,所以我在這里不處理它。
資料
df1 <- structure(list(time1 = c("2012-04-25 17:40:00", "2012-04-25 18:40:00"),
weight = 82:81), class = "data.frame", row.names = c(NA, -2L))
df2 <- structure(list(time2 = "2012-04-25 17:45:00", d1 = 1L, d2 = 0L, d3 = 1L),
class = "data.frame", row.names = c(NA, -1L))
uj5u.com熱心網友回復:
一種可能的方法:
library(tidyverse)
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
df1 <- tribble(
~time1, ~weight,
"2012-04-25 17:40:00", 82,
"2012-04-25 18:40:00", 81
) |> rename(time = time1)
df2 <- tribble(
~time2, ~d1, ~d2, ~d3,
"2012-04-25 17:45:00", 1, 0, 1
)|> rename(time = time2)
bind_rows(df1, df2) |>
mutate(time = ymd_hms(time)) |>
arrange(time) |>
fill(-weight) |>
filter(!is.na(weight)) |>
mutate(across(-time, ~if_else(is.na(.), 0, .)))
#> # A tibble: 2 × 5
#> time weight d1 d2 d3
#> <dttm> <dbl> <dbl> <dbl> <dbl>
#> 1 2012-04-25 17:40:00 82 0 0 0
#> 2 2012-04-25 18:40:00 81 1 0 1
由reprex 包于 2022-05-23 創建(v2.0.1)
uj5u.com熱心網友回復:
由于您實際上并沒有加入任何東西,您只是連接兩個資料幀,您可以先這樣做,然后修復錯誤。例如。給定你的資料
df1=read.table(text="
time1 weight
'2012-04-25 17:40:00' 82
'2012-04-25 18:40:00' 81",h=T)
df1$time1=as.POSIXct(df1$time1)
df2=read.table(text="
time2 d1 d2 d3
'2012-04-25 17:45:00' 1 0 1",h=T)
df2$time2=as.POSIXct(df2$time2)
你可以做
df3=cbind(df1,df2)
df3[df3$time2>df3$time1,grepl("d",colnames(df3))]=0
time1 weight time2 d1 d2 d3
1 2012-04-25 17:40:00 82 2012-04-25 17:45:00 0 0 0
2 2012-04-25 18:40:00 81 2012-04-25 17:45:00 1 0 1
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480413.html
上一篇:R格式資料框重復ID和冗余資訊
