我在函数中使用 dplyr
arrange
时遇到问题。
combine_dfs
和 combine_dfs_1
不起作用,
combine_dfs_2
有效,但我不明白为什么会这样。
所有这些函数应该组合 2 个 tibbles,然后根据变量排序
time
。
suppressPackageStartupMessages(library(dplyr))
df1 <- tibble(time=c(0,2),val="df1")
df2 <- tibble(time=c(1,3),val="df2")
combine_dfs <- function(...){
data <- list(...)
bind_rows(data) |>
arrange("time")
}
combine_dfs(df1,df2)
#> # A tibble: 4 × 2
#> time val
#> <dbl> <chr>
#> 1 0 df1
#> 2 2 df1
#> 3 1 df2
#> 4 3 df2
combine_dfs_1 <- function(...){
data <- list(...)
bind_rows(data) -> xx
xx |>
arrange("time")
}
combine_dfs_1(df1,df2)
#> # A tibble: 4 × 2
#> time val
#> <dbl> <chr>
#> 1 0 df1
#> 2 2 df1
#> 3 1 df2
#> 4 3 df2
combine_dfs_2 <- function(...){
data <- list(...)
bind_rows(data) ->
xx
xx |>
arrange(xx,"time")
}
combine_dfs_2(df1,df2)
#> # A tibble: 4 × 2
#> time val
#> <dbl> <chr>
#> 1 0 df1
#> 2 1 df2
#> 3 2 df1
#> 4 3 df2
创建于 2024-02-16,使用 reprex v2.1.0
你可以尝试一下我接下来展示的内容。例如,
ttime
变量上没有引号。 (旁注:我希望您允许我重命名一下,以便变量和对象名称不会获得“基本”函数名称)。
library(dplyr)
df1 <- tibble(ttime = c(0,2), val = "df1")
df2 <- tibble(ttime = c(1,3), val = "df2")
bind_rows(list(df1, df2)) %>%
arrange(ttime)
combine_dfs <- function(...){
dat <- list(...)
dplyr::bind_rows(dat) |>
arrange(ttime)
}
combine_dfs(df1,df2)
## this gives:
## A tibble: 4 × 2
# ttime val
# <dbl> <chr>
#1 0 df1
#2 1 df2
#3 2 df1
#4 3 df2