简体   繁体   English

R中带有NA的双for循环

[英]Double for loop with NA in R

I have a couple of questions with my R script. 我的R脚本有几个问题。 I have a database with many series which have NA and numeric values. 我有一个包含许多序列的数据库,这些序列具有NA和数值。 I would like to replace the NA by a 0 from the moment we have a numeric value but keep the NA if the serie is not started. 我想从有数值开始就将NA替换为0,但如果不开始意甲,则保留NA。

As we see below, for example in the second column I would like to keep the 2 first NA but replace the fourth by 0. 如下所示,例如在第二列中,我想保留第一个2 NA,但将第四个NA替换为0。

example

There is my script, but it doesn't work 有我的脚本,但是不起作用

my actual script 我的实际剧本

It would be very kind to have some suggestions 提出一些建议会很高兴

Many thanks 非常感谢

ER ER

In case you, or anyone else, want to avoid for loops: 如果您或其他任何人想要避免for循环:

# example dataset
df = data.frame(x1 = c(23,NA,NA,35),
                x2 = c(NA,NA,45,NA),
                x3 = c(4,34,NA,5))

# function to replace NAs not in the beginning of vector with 0
f = function(x) { x[is.na(x) & cumsum(!is.na(x)) != 0] = 0; x }

# apply function and save as dataframe
data.frame(sapply(df, f))

#   x1 x2 x3
# 1 23 NA  4
# 2  0 NA 34
# 3  0 45  0
# 4 35  0  5

Or using tidyverse and the same function f : 或者使用tidyverse和相同的函数f

library(tidyverse)

df %>% map_df(f)

# # A tibble: 4 x 3
#     x1    x2    x3
#   <dbl> <dbl> <dbl>
# 1   23.   NA     4.
# 2    0.   NA    34.
# 3    0.   45.    0.
# 4   35.    0.    5.

if this is your dataset: 如果这是您的数据集:

ORIGINAL_DATA <- data.frame(X1 = c(23, NA, NA, 35), 
                            X2 = c(NA, NA, 45, NA), 
                            X3 = c(4, 34, NA, 5))

This could probably work: 这可能可行:

for(i in 1:ncol(ORIGINAL_DATA)) {
  for (j in 1:nrow(ORIGINAL_DATA)) {
    if(!is.na(ORIGINAL_DATA[j, i])) {
      ORIGINAL_DATA[c(j:nrow(ORIGINAL_DATA)), i] <- ifelse(is.na(ORIGINAL_DATA[c(j:nrow(ORIGINAL_DATA)), i]), 0, ORIGINAL_DATA[c(j:nrow(ORIGINAL_DATA)), i])

      # To end this for-loop
      j <- nrow(ORIGINAL_DATA)
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM