select columns from a df in r

You can select columns from a data.frame in R by using indexing or subsetting. Here are some examples:

  1. Using the dollar sign and column name:
main.r
df$column_name
15 chars
2 lines
  1. Using column index with brackets:
main.r
df[, column_index]
19 chars
2 lines
  1. Using column name with brackets:
main.r
df[, "column_name"]
20 chars
2 lines
  1. Using column names with brackets:
main.r
df[, c("column1", "column2", "column3")]
41 chars
2 lines

Example:

main.r
# create a sample data frame
df <- data.frame(name = c("John", "Jane", "Alice"),
                 age = c(25, 30, 35),
                 salary = c(50000, 60000, 70000),
                 gender = c("male", "female", "female"))

# select the age and gender columns
age_gender <- df[, c("age", "gender")]
302 chars
9 lines

In this example, we created a data frame with columns "name", "age", "salary", and "gender". We then used column names "age" and "gender" to create a new data frame age_gender that contains only these two columns.

gistlibby LogSnag