基于下面的代码和数据,如何将列NAs中的a替换为基于列id中的特定ids的Transportation Element Maps 2012
代码:
# Sample df
df = structure(list(id = c(1, 2, 3, 4, 5, 6, 7), a = c("a", "Transportation Element Maps 2012", NA, NA, NA, NA, NA)), class = "data.frame", row.names = c(NA,
-7L))
# Desired df
df1 = structure(list(id = c(1, 2, 3, 4, 5, 6, 7), a = c("a", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", "Transportation Element Maps 2012", NA)), class = "data.frame", row.names = c(NA,
-7L))
# Current approach which throws an error
df1 = df %>% ifelse(id %in% 3:6) %>% mutate(a %in% NA, "Transportation Element Maps 2012")
# Error
Error in ifelse(., reference_number %in% 3:6) :
'list' object cannot be coerced to type 'logical'发布于 2022-10-04 15:18:55
使用is.na查找返回逻辑向量的NA元素,并将id %in% 3:6保存在mutate中。
library(dplyr)
df %>%
mutate(a = ifelse(id %in% 3:6 & is.na(a),
"Transportation Element Maps 2012", a))发布于 2022-10-04 15:33:46
您可以使用replace函数,并使用c将3:6和NA组合在一起,如下所示:
library(dplyr)
df |>
mutate(a = replace(a, id %in% c(3:6, NA), "Transportation Element Maps 2012"))https://stackoverflow.com/questions/73950081
复制相似问题