Soit le data frame suivant :
Code : Tout sélectionner
> col1 <- c(1,1,2,2)
> col2 <- c("ab", "cd", "ef", "gh")
> col3 <- c(9, 8, 7, 6)
> data <- data.frame(col1=col1, col2=col2, col3=col3)
> data
col1 col2 col3
1 1 ab 9
2 1 cd 8
3 2 ef 7
4 2 gh 6
Comment extraire rapidement le sous data frame formé des lignes qui ont un 1 dans col1?
Ceci fonctionne mais est laborieux :
Code : Tout sélectionner
> data2 <- data.frame(col1=col1[col1==1], col2=col2[col1==1],
col3=col3[col1==1])
> data2
col1 col2 col3
1 1 ab 9
2 1 cd 8
Enfin c'est un mauvais exemple car ici il suffit d'extraire les 2 premières lignes, mais si les 1 étaient "dispersés" sur la 1ère colonne ? Bref comment extraire avec la condition [col1==1] ?
Merci pour votre aide.
SL
PS : J'ai essayé ceci et je ne comprends pas les résultats de ces commandes :
Code : Tout sélectionner
> data3 <- data[col1==1]
> data3
col1 col2
1 1 ab
2 1 cd
3 2 ef
4 2 gh
> data4 <- data.frame(data)[col1==1]
> data4
col1 col2
1 1 ab
2 1 cd
3 2 ef
4 2 gh