gpt4 book ai didi

r - NA 替换为空格

转载 作者:行者123 更新时间:2023-12-03 02:03:20 24 4
gpt4 key购买 nike

我使用了相同的方法将 NA 替换为空格或其他字符,但由于某种原因,这个方法不起作用。我想将数据框中的 NA 替换为空白(年份和年度列)。我做错了什么?

shad.92 <- structure(list(year = c(1992, NA, NA, NA, NA), type = c("all age abundance index", 
"adjusted number of fish older than age 0 measured", "adjusted total number of fish measured",
"percent YOY", "YOY abundance index"), September = c(755, 0,
565, 100, 755), October = c(530, 0, 434, 100, 530), November = c(463,
0, 338, 100, 463), December = c(266, 1, 136, 99.3, 264), Annual = c(2014,
NA, NA, NA, 2012)), row.names = c(NA, -5L), class = c("tbl_df",
"tbl", "data.frame"))

我尝试过,但没有成功:

shad.92 <- shad.92[is.na(shad.92)] <- ""

然后我尝试了从年份开始的一列:

shad.92$year <- as.character(shad.92$year)
shad.92$year[is.na(shad.92$year)] <- " "
shad.92

但我得到的是引号而不是空格 ("")

最佳答案

我们可以将 mutate_atreplace_na 一起使用

library(dplyr)
library(tidyr)
shad.92 %>%
mutate_at(vars(year, Annual), replace_na, '')
# A tibble: 5 x 7
# year type September October November December Annual
# <chr> <chr> <dbl> <dbl> <dbl> <dbl> <chr>
#1 "1992" all age abundance index 755 530 463 266 "2014"
#2 "" adjusted number of fish older than age 0 measured 0 0 0 1 ""
#3 "" adjusted total number of fish measured 565 434 338 136 ""
#4 "" percent YOY 100 100 100 99.3 ""
#5 "" YOY abundance index 755 530 463 264 "2012"

关于r - NA 替换为空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59955561/

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