Menu
Coddy logo textTech

Columns and Rows

Part of the Logic & Flow section of Coddy's R journey. Lesson 43 of 64.

df$col and df[["col"]] return a column as a plain vector, so every vector function works on it. [[ ]] accepts a column name stored in a variable:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
print(people$age)
print(mean(people$age))
col <- "city"
print(people[[col]])

Output:

[1] 36 22 41
[1] 33
[1] "london" "paris"  "rome"  

Square brackets take [row, column], like a matrix. An empty side selects everything, and columns can be picked by name:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
print(people[2, ])
print(people[, c("name", "city")])

Output:

  name age  city
2   bo  22 paris
  name   city
1  ada london
2   bo  paris
3   cy   rome

One cell is df[row, column], and assigning to it changes the value. Assigning to a whole column works the same way:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
print(people[3, "age"])
people[3, "age"] <- 42
people$city <- toupper(people$city)
print(people)

Output:

[1] 41
  name age   city
1  ada  36 LONDON
2   bo  22  PARIS
3   cy  42   ROME

To go through the rows one by one, loop over seq_len(nrow(df)) and read each cell with df[i, "col"] or df$col[i]:

people <- data.frame(
  name = c("ada", "bo", "cy"),
  age = c(36, 22, 41),
  city = c("london", "paris", "rome")
)
for (i in seq_len(nrow(people))) {
  cat(people$name[i], "lives in", people[i, "city"], "\n")
}

Output:

ada lives in london 
bo lives in paris 
cy lives in rome 
challenge icon

Challenge

Easy

Complete person_card(df, i). Return one line per column for row i, name: bo, with the column name and the value in that row, in the order of the columns.

The supplied code reads the table from the input with read.csv(text = input): the first line holds the column names and every following line is one row, with values separated by commas. The last input line holds i, and the code prints each returned line.

Try it yourself

person_card <- function(df, i) {
  # Write your code here
  character(0)
}

# Supplied input/output code: keep it as it is
input <- suppressWarnings(readLines(file("stdin")))
df <- read.csv(text = input[-length(input)])
i <- as.numeric(input[length(input)])
cat(person_card(df, i), sep = "\n")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online R compiler