gpt4 book ai didi

r - 如果列中有一定数量的连续 NA,则替换这些值

转载 作者:行者123 更新时间:2023-12-04 23:13:52 30 4
gpt4 key购买 nike

我有一个名为 meanSR_strong 的列另一个叫 meanSR_weak .如果 meanSR_strong 中有 10 个或更多连续的 NA列,我想用来自 meanSR_weak 的值替换这些值列,即使这些替换的值也是 NA。如果 meanSR_strong 中存在连续的 NAs列,那么我不需要做任何替换。

比如第3-6行都是NA,但那只是连续的4行,所以没关系。然而,第 15-28 行都是不适用的(而且连续超过 10 个),所以我想从 meanSR_weak 中提取值柱子。

我知道如何替换所有的 NA,但我还没有想出一个很好的编码方法!

这是我的数据

x=structure(list(meanSR_strong = c(NA, 0.376009009009009, NA, NA, 
NA, NA, 0.615585585585586, NA, 0.607354054054054, 0.590210810810811,
0.57005045045045, 0.596616216216216, 0.584066666666667, 0.538597297297297,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 0.639010810810811,
0.634272972972973), meanSR_weak = c(0.574724324324324, 0.562030630630631,
0.586247747747748, NA, NA, NA, 0.615585585585586, NA, 0.607354054054054,
0.590210810810811, 0.57005045045045, 0.596616216216216, 0.608510810810811,
0.538597297297297, NA, NA, NA, 0.555463063063063, 0.376715315315315,
NA, NA, NA, NA, NA, NA, 0.60972972972973, NA, NA, 0.639010810810811,
0.634272972972973), cloud.pct_strong = c(100, 36.036036036036,
98.1981981981982, 100, 100, 100, 0, 100, 0, 0, 0, 0, 3.6036036036036,
0, NA, NA, 100, 67.5675675675676, 100, 100, NA, 100, 100, 100,
100, 74.7747747747748, 100, 100, 0, 0), cloud.pct_weak = c(0,
0, 0, 100, 100, 100, 0, 100, 0, 0, 0, 0, 0, 0, NA, NA, 100, 0,
36.036036036036, 67.5675675675676, NA, 100, 100, 100, 100, 0.900900900900901,
100, 60.3603603603604, 0, 0), date = structure(c(951868800, 951955200,
952041600, 952128000, 952214400, 952300800, 952387200, 952473600,
952560000, 952646400, 952732800, 952819200, 952905600, 952992000,
953078400, 953164800, 953251200, 953337600, 953424000, 953510400,
953596800, 953683200, 953769600, 953856000, 953942400, 954028800,
954115200, 954201600, 954288000, 954374400), class = c("POSIXct",
"POSIXt"), tzone = "UTC")), .Names = c("meanSR_strong", "meanSR_weak",
"cloud.pct_strong", "cloud.pct_weak", "date"), row.names = c(NA,
-30L), class = c("tbl_df", "tbl", "data.frame"))

最佳答案

temp = inverse.rle(with(rle(is.na(x$meanSR_strong)),
list(lengths = lengths,
values = replace(values, which(lengths > 10), 2))))
replace(x$meanSR_strong, temp == 2, x$meanSR_weak[temp == 2])
# [1] NA 0.3760090 NA NA NA
# [6] NA 0.6155856 NA 0.6073541 0.5902108
#[11] 0.5700505 0.5966162 0.5840667 0.5385973 NA
#[16] NA NA 0.5554631 0.3767153 NA
#[21] NA NA NA NA NA
#[26] 0.6097297 NA NA 0.6390108 0.6342730

关于r - 如果列中有一定数量的连续 NA,则替换这些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697205/

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