Come si usa "non è na"? nella r


È possibile utilizzare la seguente sintassi per restituire valori in R che non siano valori NA:

 #return only values that are not NA
x <- x[ ! is. na (x)]

Gli esempi seguenti mostrano come utilizzare questa sintassi sia con i vettori che con i frame di dati in R.

Esempio 1: restituisci valori che non sono NA nel vettore

Il codice seguente mostra come restituire valori da un vettore che non siano NA:

 #createvector
x <- c(1, 24, NA, 6, NA, 9)

#return only values that are not NA
x <- x[ ! is. na (x)]

[1] 1 24 6 9

Esempio 2: restituisce righe che non sono NA in una colonna nel frame di dati

Il codice seguente mostra come restituire righe in un frame di dati che non hanno un valore NA in una colonna specifica:

 #create data frame
df <- data. frame (x=c(1, 24, NA, 6, NA, 9),
                 y=c(NA, 3, 4, 8, NA, 12),
                 z=c(NA, 7, 5, 15, 7, 14))

#view data frame
df

   X Y Z
1 1 NA NA
2 24 3 7
3 NA 4 5
4 6 8 15
5 NA NA 7
6 9 12 14

#remove rows with NA in z column
df <- df[ ! (is. na (df$z)), ]

#view data frame
df

   X Y Z
2 24 3 7
3 NA 4 5
4 6 8 15
5 NA NA 7
6 9 12 14

Esempio 3: restituisce righe che non sono NA in più colonne

Il codice seguente mostra come restituire righe in un frame di dati che non hanno un valore NA in una delle numerose colonne specifiche:

 #create data frame
df <- data. frame (x=c(1, 24, NA, 6, NA, 9),
                 y=c(NA, 3, 4, 8, NA, 12),
                 z=c(NA, 7, 5, 15, 7, 14))

#view data frame
df

   X Y Z
1 1 NA NA
2 24 3 7
3 NA 4 5
4 6 8 15
5 NA NA 7
6 9 12 14

#remove rows with NA in x or y column
df <- df[ ! (is. na (df$x)) & ! (is. na (df$y)), ]

#view data frame
df

   X Y Z
2 24 3 7
4 6 8 15
6 9 12 14

Esempio 4: restituisce righe che non sono NA in nessuna colonna

Il codice seguente mostra come restituire righe in un frame di dati che non hanno un valore NA in nessuna colonna:

 #create data frame
df <- data. frame (x=c(1, 24, NA, 6, NA, 9),
                 y=c(NA, 3, 4, 8, NA, 12),
                 z=c(NA, 7, 5, 15, 7, 14))

#view data frame
df

   X Y Z
1 1 NA NA
2 24 3 7
3 NA 4 5
4 6 8 15
5 NA NA 7
6 9 12 14

#remove rows with NA in any column
df <- na. omitted (df)

#view data frame
df

   X Y Z
2 24 3 7
4 6 8 15
6 9 12 14

Risorse addizionali

Come sostituire i NA con stringhe in R
Come imputare tutti i valori mancanti in R

Aggiungi un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *