gpt4 book ai didi

r - 使用 unite 和 str_to_title : NAs united as strings and go undetected as NAs R

转载 作者:行者123 更新时间:2023-12-04 10:16:05 25 4
gpt4 key购买 nike

我在两个联合的列中有 NA。在合并之前,我使用 str_to_title 来创建值的一致性。

问题是现在 NA 未注册为 NA,它们已合并为字符串。 IE。

City         State        City, State
Denver CO Denver, CO
NA NA NA, NA
Los Angeles CA Los Angeles, CA

我尝试使用 df[df$col == "NA, NA"] <- NA 对其进行硬编码那没有用。

最佳答案

我们可以创建一个索引然后更新

library(stringr)
i1 <- !(is.na(df$City) & is.na(df$State))
df$City_State[i1] <- with(df[i1,], paste(City, State, sep=', '))

如果我们使用 str_c ,那么它会返回 NA如果有任何 NA
with(df, str_c(City, State, sep=", "))
#[1] "Denver, CO" NA "Los Angeles, CA"

数据
df <- structure(list(City = c("Denver", NA, "Los Angeles"),
State = c("CO",
NA, "CA")), class = "data.frame", row.names = c(NA, -3L))

关于r - 使用 unite 和 str_to_title : NAs united as strings and go undetected as NAs R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050416/

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