I have a df converted to a tibble. Let’s say I am interested to extract a range of values from the Week column say between rows 1 and 3. In case of a df I can simply do df[1:3, 7], but how can I do this in case of a tibble?
Code
library(tidyverse)
# Create sample data
Date = c("2014-04-08", "2014-06-04", "2014-04-30",
"2014-05-30", "2014-05-01")
lat = as.numeric(c("45.53814", "45.51076", "45.43560", "45.54332",
"45.52234"))
lon = as.numeric(c("-73.63672", "-73.61029", "-73.60100",
"-73.56000 ", "-73.59022"))
id = as.numeric(c("1", "2", "3", "4", "5"))
# Create a df from the above columns and add date columns
df = data.frame(id, lat, lon, Date)
df$Year = lubridate::year(df$Date)
df$Month = lubridate::month(df$Date, label = TRUE, abbr=FALSE)
df$Week = lubridate::week(df$Date)
df$Date = as.Date(df$Date)
# Create a tibble
dft = as_tibble(df)
>Solution :
Use [[ or $ with name to get the column as a vector – tibble by default use drop = FALSE whereas data.frame/matrix have drop = TRUE when there is a single column/row
dft[1:3,][[7]]
[1] 14 23 18
dft[1:3,]$Week
[1] 14 23 18
Or if we want to use tidyverse approaches, use pull
library(dplyr)
dft %>%
slice(1:3) %>%
pull(7)
As @Baraliuh mentioined in the comments, extraction methods for tibble are mentioned here