Je souhaite supprimer dans une matrice nommé temp les lignes ou:
-> les valeurs de la colonnes 2 sont < à 501 & > à 650
& en meme temps
-> les valeurs de la colonnes 3 sont < à 680 & > à 798
Modérateur : Groupe des modérateurs
Code : Tout sélectionner
> ted <- matrix(rnorm(24),6,4)
> ted
[,1] [,2] [,3] [,4]
[1,] 0.09452 -0.1434 0.1753 0.2391
[2,] 1.08918 -1.2438 1.0476 -1.7786
[3,] -0.02264 0.5490 0.5834 -0.4604
[4,] 0.15344 -0.8829 -1.2376 0.1399
[5,] 2.71974 -0.0754 -1.7309 -0.6627
[6,] -0.09254 0.9463 1.1513 1.0201
> ted[ted[,3]>0,]
[,1] [,2] [,3] [,4]
[1,] 0.09452 -0.1434 0.1753 0.2391
[2,] 1.08918 -1.2438 1.0476 -1.7786
[3,] -0.02264 0.5490 0.5834 -0.4604
[4,] -0.09254 0.9463 1.1513 1.0201
> ted[,ted[3,]>0]
[,1] [,2]
[1,] -0.1434 0.1753
[2,] -1.2438 1.0476
[3,] 0.5490 0.5834
[4,] -0.8829 -1.2376
[5,] -0.0754 -1.7309
[6,] 0.9463 1.1513
> ted[(ted[,3]>0) & (ted[,3] < 1.5),(ted[2,]>0) & (ted[2,] < 1.5)]
[,1] [,2]
[1,] 0.09452 0.1753
[2,] 1.08918 1.0476
[3,] -0.02264 0.5834
[4,] -0.09254 1.1513
>
Code : Tout sélectionner
> selrow <- (ted[,3]>0) & (ted[,3] < 1.5)
> selcol <- (ted[2,]>0) & (ted[2,] < 1.5)
> ted[selrow,selcol]
[,1] [,2]
[1,] 0.09452 0.1753
[2,] 1.08918 1.0476
[3,] -0.02264 0.5834
[4,] -0.09254 1.1513
>
Code : Tout sélectionner
> selrow <- (ted[,3]>0) & (ted[,3] < 1.5) & (ted[,4] > 0.5)
> selcol <- (ted[2,]>0) & (ted[2,] < 1.5)
> ted[selrow,selcol]
[1] -0.09254 1.15127
>
comment on fait pour remplacer les NA par des zéros dans une matrice quelconque?
Code : Tout sélectionner
NaReplace <- function(x,valnew){
if(is.vector(x))
x[is.na(x)] <- rep(valnew,length(x[is.na(x)]))
else
for(i in 1:ncol(x))
x[is.na(x[,i]),i] <- rep(valnew,length(x[is.na(x[,i]),i]))
return(x)
}
Code : Tout sélectionner
# pour matrix et data.frame
ted <- matrix(rnorm(24),4,6)
ted[1,2] <-NA
ted[3,4] <-NA
ted
newted <- NaReplace(ted,0)
newted
# pour vector
ted <- rnorm(10)
ted[c(1, 5,9)] <-rep(NA,3)
ted
newted <- NaReplace(ted,0)
newted
Code : Tout sélectionner
> mat <- abs(c(0:3, -1:2, -2:1, -3:0) )
> mat
[1] 0 1 2 3 1 0 1 2 2 1 0 1 3 2 1 0
> attributes(mat)
NULL
> dim(mat) <- c(4, 4)
> mat
[,1] [,2] [,3] [,4]
[1,] 0 1 2 3
[2,] 1 0 1 2
[3,] 2 1 0 1
[4,] 3 2 1 0
> attributes(mat)
$dim
[1] 4 4
> mat[mat == 0] <- NA
> mat
[,1] [,2] [,3] [,4]
[1,] NA 1 2 3
[2,] 1 NA 1 2
[3,] 2 1 NA 1
[4,] 3 2 1 NA
> mat[is.na(mat)] <- 0
> mat
[,1] [,2] [,3] [,4]
[1,] 0 1 2 3
[2,] 1 0 1 2
[3,] 2 1 0 1
[4,] 3 2 1 0
Retourner vers « Archives : Manipulation de données avec R »
Utilisateurs parcourant ce forum : Aucun utilisateur enregistré et 1 invité