Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extracting range of values from a tibble in R

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading