Skip to content
Prev 393624 / 398503 Next

Removing variables from data frame with a wile card

?s 16:54 de 15/01/2023, Sorkin, John escreveu:
Hello,

Actually, Bill had addressed this in his post yesterday [1].
With your example,


one <- rep(1,10)
two <- rep(2,10)
three <- rep(3,10)
mydata <- data.frame(one=one, two=two, three=three)

ColumToDelete <- grep("fo",colnames((mydata)))
ColumToDelete
#> integer(0)
ColumToDeleteLogical <- grepl("fo",colnames((mydata)))
ColumToDeleteLogical
#> [1] FALSE FALSE FALSE

# Drop the column whose name starts with "fo"
# empty data.frame
mydata[, -ColumToDelete]
#> data frame with 0 columns and 10 rows

# nothing is deleted
mydata[, !ColumToDeleteLogical]
#>    one two three
#> 1    1   2     3
#> 2    1   2     3
#> 3    1   2     3
#> 4    1   2     3
#> 5    1   2     3
#> 6    1   2     3
#> 7    1   2     3
#> 8    1   2     3
#> 9    1   2     3
#> 10   1   2     3



[1] https://stat.ethz.ch/pipermail/r-help/2023-January/476682.html


Hope this helps,

Rui Barradas