我想做一個接受這些資料的函式
now changed before
"12ab" "yes" "21ba"
"34de" "no"
"56fg" "yes" "gf65"
"78hi" "no" NA
并把它變成
now changed before
"12ab" "yes" "21ba"
"34de" "no" "34de"
"56fg" "yes" "gf65"
"78hi" "no" "78hi"
所以如果 before 是空的,我想 before 取 now 的值(假設如果它沒有改變,它一定是一樣的。
我想使用一個函式,因為我想將它應用于更多列對。
我試過這個:
library(purrr)
library(dplyr)
fun <- function(data, x, y) {
coalesce(case_when(data[[y]] == NA | data[[y]] == '' ~ data[[x]], data[[y]])
}
df[c("before", "before1")] <- map2(c("now", "now1"),c("before", "before1") ~ fun(df, .x, .y))
但它什么也沒做。
uj5u.com熱心網友回復:
您可以使用以下方法將空字串轉換為 NAdplyr::na_if并合并dplyr::coalesce:
library(dplyr)
df %>%
na_if("") %>%
mutate(before = coalesce(before, now))
# now changed before
# 1 12ab yes 21ba
# 2 34de no 34de
# 3 56fg yes gf65
# 4 78hi no 78hi
作為一個函式,你可以有:
f <- function(data, x, y){
data %>%
na_if("") %>%
mutate(before = coalesce({{x}}, {{y}}))
}
f(df, before, now)
uj5u.com熱心網友回復:
請參閱我上面關于na.strings在讀取資料時定義的評論。然后你可以使用base R來填充缺失的資料:
df$before[is.na(df$before)] <- df$now[is.na(df$before)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438966.html
