我正在尋找替換mutate_,mutate因為現在有棄用警告,并且不確定如何使用我在 Stack Overflow 上找到的一些答案。這個答案有一個已棄用的quosure問題,并且不確定如何應用這個問題。
library(tibble)
library(dplyr)
library(magrittr)
library(rlang)
# two data frames/tibbles
df1 <-
data.frame(
w = c(0,9,8),
x = c(1,2,3),
y = c(4,5,6)
) %>% tibble()
df2 <-
data.frame(
x = c(9,9,9),
y = c(1,1,1),
z = c(6,6,6)
) %>% tibble()
# the original function
swapThem <- function(to, from) {
cols <- colnames(from)
if (length(cols) != 0) {
# Loop through `from` columns and if there's a match in `to`, copy and paste
# it into `to`
for (i in seq_along(cols)) {
col <- cols[i]
if (col %in% colnames(to)) {
print(col)
dots <-
stats::setNames(list(lazyeval::interp(
~ magrittr::use_series(from, x), x = as.name(col)
)), col)
to <- to %>%
#dplyr::mutate(.dots = dots)
dplyr::mutate_(.dots = dots)
} else {
next
}
}
}
return(to)
}
uj5u.com熱心網友回復:
這是一個更簡單的基本 R 替代方案 -
swapThem <- function(to, from) {
cols <- intersect(colnames(to), colnames(from))
if(length(cols)) to[cols] <- from[cols]
to
}
swapThem(df1, df2)
# A tibble: 3 × 3
# w x y
# <dbl> <dbl> <dbl>
#1 0 9 1
#2 9 9 1
#3 8 9 1
當我運行你的代碼時,輸??出是相似swapThem(df1, df2)的
#[1] "x"
#[1] "y"
# A tibble: 3 × 3
# w x y
# <dbl> <dbl> <dbl>
#1 0 9 1
#2 9 9 1
#3 8 9 1
uj5u.com熱心網友回復:
有更簡單的方法可以做到這一點(例如,請參閱 Ronak Shah 的基本 R 方法),但是由于您特別詢問了如何從 to 切換mutate_,mutate您可以通過這種方式調整原始代碼:
swapThem <- function(to, from) {
cols <- colnames(from)
if (length(cols) != 0) {
# Loop through `from` columns and if there's a match in `to`, copy and paste
# it into `to`
for (i in seq_along(cols)) {
col <- cols[i]
if (col %in% colnames(to)) {
to <- to %>% dplyr::mutate(!!sym(col) := from[[col]])
} else {
next
}
}
}
return(to)
}
請注意,您也可以使用{{}},如下所示:
to <- to %>% dplyr::mutate({{col}} := from[[col]])
這是另一種整潔的方法,它使用bind_cols. 重定位是為了確保to保留列的順序
swapThem <- function(to,from) {
bind_cols(
to %>% select(all_of(setdiff(colnames(to), colnames(from)))),
from %>% select(all_of(intersect(colnames(to), colnames(from))))
) %>%
relocate(colnames(to))
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/445309.html
上一篇:如何根據R中組的最大值聚合資料框
