How can I get the last 3 columns in R?

Viewed 25
2 Answers

Here is a way with readr::read_csv. First get the column names by reading only the first row with scan. Then read the data selecting the wanted columns

col_names <- scan(fl, nlines = 1L, what = character(), sep = ",")
n <- length(col_names)
wanted <- col_names[(n - 2L):n]

library(readr)

df1 <- read_csv(fl, col_select = all_of(wanted))
head(df1)
## A tibble: 6 × 3
#     o3  time season
#  <dbl> <dbl> <chr> 
#1  4.03     1 winter
#2  4.58     2 winter
#3  3.40     3 winter
#4  3.94     4 winter
#5  4.40     5 winter
#6  5.98     6 winter

If your file "chicago-nmmaps.csv" is in your working directory, you can

  1. read the file into R (file).
  2. select only the last three columns (file2).

file <- readr::read_delim("chicago-nmmaps.csv", delim=",")
file2 <- file[ , (ncol(file)-2):ncol(file)]

Related