Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 0 0 0 0.2 0 2 0 0 0 0.2 0 3 0 0 0 0.2 0 4 0 0 0 0.2 0 5 0 0 0 0.2 0 6 0 0 0 0.4 0
3 Réponses :
Supprimez col
des names
de mydat
et remplacez toutes les autres valeurs par 0.
library(dplyr) mydat %>% mutate(across(-all_of(col), ~0))
Dans dplyr
vous pouvez utiliser à across
comme:
col = "Petal.Width" mydat[setdiff(names(mydat), col)] <- 0 mydat # Sepal.Length Sepal.Width Petal.Length Petal.Width Species #1 0 0 0 0.2 0 #2 0 0 0 0.2 0 #3 0 0 0 0.2 0 #4 0 0 0 0.2 0 #5 0 0 0 0.2 0 #6 0 0 0 0.4 0
Impressionnant. Est-il possible de stocker cela sous mydat2
? Ou devrais-je simplement faire une copie de mydat
utilisant d'abord mydat2 <- mydat
, puis faire mydat2 %>% mutate(across(-all_of(col), ~0))
mydat2 <- mydat %>% mutate(across(-all_of(col), ~0))
devrait fonctionner.
Une façon de le faire:
x <- 1:5 y <- 1:5 z <- 1:5 d <-data.frame(x,y,z) d[,-2] <- 0 #zero out all columns but column 2 d x y z 0 1 0 0 2 0 0 3 0 0 4 0 0 5 0
Vous pouvez également essayer celui-ci:
head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa iris[,-4] <- 0 head(iris) Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 0 0 0 0.2 0 2 0 0 0 0.2 0 3 0 0 0 0.2 0 4 0 0 0 0.2 0 5 0 0 0 0.2 0 6 0 0 0 0.4 0