gpt4 book ai didi

r - 将多列粘贴到一列中,但删除任何 NA、空白或重复值

转载 作者:行者123 更新时间:2023-12-04 10:39:34 24 4
gpt4 key购买 nike

我有这样的数据:

dat <- data.frame(SOURCES1 = c("123 Name, 123 Rd, City, State", 
"354 Name, 354 Rd, City, State",
NA,"",""),
SOURCES2 = c("","",
"321 Name, 321 Rd, City, State",
"678 Name, 678 Rd, City, State",
""),
SOURCES3 = c("","",NA,
"678 Name, 678 Rd, City, State",
NA),
SOURCES4 = c("","","",NA,NA),
SOURCES5 = c("","","",NA,NA))

我正在寻找一个看起来像这样的专栏:

"123 Name, 123 Rd, City, State"
"354 Name, 354 Rd, City, State"
"321 Name, 321 Rd, City, State"
"678 Name, 678 Rd, City, State"
NA

最佳答案

在将空格 ("") 转换为 NA 之后,我们可以合并

library(tidyverse)
dat %>%
mutate_all(funs(na_if(as.character(.), ''))) %>%
transmute(SOURCE = coalesce(!!! rlang::syms(names(.))))
# SOURCE
#1 123 Name, 123 Rd, City, State
#2 354 Name, 354 Rd, City, State
#3 321 Name, 321 Rd, City, State
#4 678 Name, 678 Rd, City, State
#5 <NA>

或者使用 purrr 中的 invoke

dat %>% 
mutate_all(funs(na_if(as.character(.), ''))) %>%
transmute(SOURCE = invoke(coalesce, .))
# SOURCE
#1 123 Name, 123 Rd, City, State
#2 354 Name, 354 Rd, City, State
#3 321 Name, 321 Rd, City, State
#4 678 Name, 678 Rd, City, State
#5 <NA>

或者使用来自base Rpnax

do.call(pmax, c(lapply(dat, function(x) replace(as.character(x), 
x=="", NA)), na.rm = TRUE))

关于r - 将多列粘贴到一列中,但删除任何 NA、空白或重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53859169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com