如何创建一个函数,用另一列中的值填充一列中的空行?

发布于 2025-01-11 17:21:30 字数 730 浏览 0 评论 0原文

我想制作一个函数来获取这些数据

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))

但它没有做任何事情。

I want to make function that takes this data

now      changed   before
"12ab"   "yes"     "21ba"
"34de"   "no"      
"56fg"   "yes"     "gf65"
"78hi"   "no"      NA

And turn it into

now      changed   before
"12ab"   "yes"     "21ba"
"34de"   "no"      "34de"
"56fg"   "yes"     "gf65"
"78hi"   "no"      "78hi"

So if before is empty, I want before to take the value of now (with the assumption that if it didn't change, it must have been the same.

I want to use a function as I want to apply it to more column pairs.

I tried this:

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))

But it doesn't do anything.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我们只是彼此的过ke 2025-01-18 17:21:30

您可以使用 dplyr::na_if 将空字符串转换为 NA,并使用 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)

You can convert empty string to NA with dplyr::na_if and coalesce with 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

As a function, you could have:

f <- function(data, x, y){
  data %>% 
    na_if("") %>% 
    mutate(before = coalesce({{x}}, {{y}}))
}

f(df, before, now)
那伤。 2025-01-18 17:21:30

请参阅上面关于在读取数据时定义 na.strings 的评论。然后你可以使用基R来填充缺失的数据:

df$before[is.na(df$before)] <- df$now[is.na(df$before)]

See my comment above about defining na.strings when reading in your data. Then you can use base R to fill in the missing data:

df$before[is.na(df$before)] <- df$now[is.na(df$before)]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文