AnyCompiler

Data Frame Manipulation

Adding a column to a data frame is just assigning to a new $ name, and because every operation you've learned already works vectorized, the new column is usually computed from existing ones in a single expression, like a comparison. Filtering rows uses the same df[rows, columns] indexing a plain vector uses, except now there are two dimensions: a logical vector in the rows slot keeps only the rows where it's TRUE, and leaving the columns slot empty keeps every column.

df <- data.frame(name = c("Ada", "Alan", "Grace"), age = c(36, 41, 85))
df$senior <- df$age > 40
print(df)
print(df[df$age > 40, ])
Output
   name age senior
1   Ada  36  FALSE
2  Alan  41   TRUE
3 Grace  85   TRUE
   name age senior
2  Alan  41   TRUE
3 Grace  85   TRUE

df$senior <- df$age > 40 added a whole new logical column in one line, computed from the age column with the same vectorized comparison from the indexing lesson. df[df$age > 40, ] — note the comma, with nothing after it — kept every column but only the rows where that condition held, dropping Ada's row entirely. Next: factors — representing categorical data as a fixed set of levels.

Practice exercise

Given df <- data.frame(name = c("Ann", "Bob", "Cid"), score = c(40, 55, 80)), add a logical column df$pass that is TRUE when score is at least 50, then print only the rows where df$pass is TRUE.