如何创建一个函数,用另一列中的值填充一列中的空行?
我想制作一个函数来获取这些数据
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 dplyr::na_if 将空字符串转换为 NA,并使用 dplyr::coalesce 进行合并:
作为一个函数,您可以:
You can convert empty string to NA with
dplyr::na_if
and coalesce withdplyr::coalesce
:As a function, you could have:
请参阅上面关于在读取数据时定义
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)]