Karl_1025
Karl_1025

Reputation: 39

R: read csv with column names in variables

I would like to read a csv file and to use the column names from variables. Of Course the strings in the variables are equal to the column names of the csv file.

The name in the column in the csv are e.g. "name" , "ps" and "year". When I just would like to read the csv and to assign column types (without any variables) I use:

library(readr)   
CarTest <- read_csv("~/_file.csv", 
                                  col_types = cols( 
                                  name = col_character(),
                                  year_a = col_character(),       
                                  ps =col_double()))

The idea is to assign the name of the columns in a variable to ensure that if the column names in the csv file are changed, just the strings of variables have to be changed, too. So, I would like to assign the column names in variables before (still the column names in the csv_file and the strings in the variables are the same). I tried different approaches: This example (hopefully) shows, that I try to paste the string of the variable car_names in the read_csv function. But obviously get is the wrong approach:

library(readr)    
car_names <- "name"      
engine_power <- "ps"
year_a <-"year" 



    CarTest <- read_csv("~/_file.csv", 
                                  col_types = cols( 

                                  get("car_names") = col_character(),
                                  get("year_a") = col_character(),       
                                  get("engine_power") =col_double()))

Thank you for your help ;)

Upvotes: 3

Views: 59498

Answers (3)

Prakhar Gurawa
Prakhar Gurawa

Reputation: 393

data1 <- read.csv("2016.csv",col.names = c("consitituency_name","candidate_surname","candidate_first_name","result","count_number","transfers","votes","total_votes","candidate_id","party"))

This code works fine on my system

Upvotes: 1

Grant Shannon
Grant Shannon

Reputation: 5055

if you just want to impose column names you could do this:

read data with no column names:

data <- read.csv(file="myfile.csv", header=FALSE, sep=",")

impose column names:

names(data) <- c('id','name','type')

view data with column names:

data

id      name    type
37707   name1   t1 
37726   name2   t2 
37737   name3   t3

Upvotes: 7

Mike Stanley
Mike Stanley

Reputation: 1480

You can just specify the column names with the col_names argument:

> library(readr)
> read_csv("example.csv", col_names = c("name", "year_a", "ps"), col_types = cols(col_character(), col_character(), col_double()))
# A tibble: 4 x 3
   name year_a    ps
  <chr>  <chr> <dbl>
1     1      2   3.0
2 test1   2017  35.5
3 test2   2018  44.5
4 test3   2019  22.0

So to use your example variables, you could just do:

library(readr)
read_csv("example.csv", col_names = c(car_names, year_a, engine_power), col_types = cols(col_character(), col_character(), col_double()))

Upvotes: 3

Related Questions