keep() enables you to put in a vector of variable names which then are kept
inside the given data frame. All other variables are dropped. Passing NA (or ".")
keeps all variables whose name is NA.
dropp() enables you to put in a vector of variable names which then are dropped
from the given data frame. All other variables are kept. Passing NA (or ".")
drops all variables whose name is NA.
Examples
# Example data frame
my_data <- dummy_data(1000)
# Call function
new_dt1 <- my_data |> keep(year, age, sex)
new_dt2 <- my_data |> keep(weight, income, education, sex, order_vars = TRUE)
new_dt3 <- my_data |> dropp(year, age, sex)
# Also works with characters
new_dt4 <- my_data |> keep("year", "age", "sex")
new_dt5 <- my_data |> dropp("year", "age", "sex")
# Or variable names stored as a character vector
var_names <- c("age", "sex", "income", "weight")
new_dt6 <- my_data |> keep(var_names)
new_dt7 <- my_data |> dropp(var_names)
# You can also keep or drop a range of variables
new_dt8 <- my_data |> keep(year, state:income)
new_dt9 <- my_data |> dropp(year, state:income)
# A colon range selects everything between the two variables inside the data
# frame. If the variables you are looking for are not stored next to each
# other, you can use a hyphen instead. It then selects all variables which
# share the same pattern in the given range, no matter where they are stored
# inside the data frame.
wide_data <- dummy_data(1000, wide = TRUE)
ranged_data <- wide_data |> keep(age1-age5)
# You can also use the colon as a placeholder for any text
start1 <- my_data |> keep("s:") # Variable names start with "s"
start2 <- my_data |> dropp("s:")
end1 <- my_data |> keep(":id") # Variable names end with "id"
end2 <- my_data |> dropp(":id")
contain1 <- my_data |> keep(":on:") # Variable names which contain "on"
contain2 <- my_data |> dropp(":on:")
# NA (or ".") is a keyword which selects all variables whose name is NA
na_data <- data.frame(a = 1:3, b = 4:6)
names(na_data) <- c(NA, "b")
new_dt10 <- na_data |> keep(NA)
new_dt11 <- na_data |> dropp(NA)
new_dt12 <- na_data |> dropp(".")
