选择数据帧不同行和列中的多个NA

时间:2018-08-24 09:31:02

标签: r dataframe selection na

我有一个具有12000行和35列的数据框,在不同的行或列中有多个NA。

我想创建一种ifelse函数来选择并将其更改为一个值(例如“ 0”或“ 9999”)。

我的问题是<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="checkForNegativeNumbers"> check For Negative Numbers</button> <br /> <div class="test"> <h2>main container</h2> <p> some sample text</p> <div class="number-container"> <p> this number is 1</p> </div> </div> <div class="test"> <h2>main container</h2> <p> some sample text</p> <div class="number-container"> <p> this number is 5</p> </div> </div> <div class="test"> <h2>main container</h2> <p> some sample text</p> <div class="number-container"> <p> this number is -32</p> </div> </div> <div class="test"> <h2>main container</h2> <p> some sample text</p> <div class="number-container"> <p> this number is -27</p> </div> </div>似乎无法在整个数据框中使用,但是我对每个单独的列进行选择并没有真正的魅力。

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

library(dplyr)

data <- tibble(a = c(1, NA, 2), b = c(NA,1,2)) # let's create some data
data
# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1    NA
2    NA     1
3     2     2

data[is.na(data)] <- 0
data
# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1     0
2     0     1
3     2     2

或使用NaN

data <- tibble(a = c(1, NaN, 2), b = c(NaN,1,2))
data
# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1   NaN
2   NaN     1
3     2     2

data[is.na(data)] <- 0 # still works the same 
data
# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1     0
2     0     1
3     2     2

如果您将"NA"作为字符串:

data <- tibble(a = c(1, "NA", 2), b = c("NA",1,2))
data[data=="NA"] <- NA # first fix and bring all to "true" NA
data[is.na(data)] <- 0 # still works the same 
data
# A tibble: 3 x 2
      a     b
  <dbl> <dbl>
1     1     0
2     0     1
3     2     2

答案 1 :(得分:1)

一种NA解决方案:

对于NaNdf <- tibble(a = c(1, NaN, 2), b = c(NA,1,2)) df %>% replace(is.na(.), 0) # A tibble: 3 x 2 a b <dbl> <dbl> 1 1. 0. 2 0. 1. 3 2. 2.

"NA"

对于"NaN"df <- tibble(a = c(1, "NaN", 2), b = c("NA",1,2)) df %>% mutate_all(funs(replace(., .=="NaN", 0))) %>% mutate_all(funs(replace(., .=="NA", 0))) %>% mutate_all(funs(as.numeric)) # A tibble: 3 x 2 a b <dbl> <dbl> 1 1. 0. 2 0. 1. 3 2. 2. 作为字符串:

$( '.WarningCount' ).parent().each(function () {
    this.style.setProperty( 'margin-left', '-1.4%', 'important' );
});