R: Import CSV with column names that contain spaces

后端 未结 3 2206
迷失自我
迷失自我 2020-12-08 15:42

CSV file looks like this (modified for brevity). Several columns have spaces in their title and R can\'t seem to distinguish them.

Alias;Type;SerialNo;DateTime;Ma         


        
相关标签:
3条回答
  • 2020-12-08 16:28

    I believe spaces get replaced by dots "." when importing CSV files. So you'd write e.g. Main.status. You can check by entering names(s_data) to see what the names are.

    0 讨论(0)
  • 2020-12-08 16:31

    Unless you specify check.names=FALSE, R will convert column names that are not valid variable names (e.g. contain spaces or special characters or start with numbers) into valid variable names, e.g. by replacing spaces with dots. Try names(s_data). If you do use check.names=TRUE, then use single back-quotes (`) to surround the names.

    I would also recommend using rename from the reshape package.

    s_data <- read.csv2( file=f_name )
    library(reshape)
    s_df <- rename(s_data,ID="scada_id",
                   PlantNo="plant",DateTime="date",Main.status="main_code",
                   Additional.status="seco_code",MainStatustext="main_text",
                   AddStatustext="seco_test",Duration="duration")
    

    For what it's worth, the tidyverse tools (i.e. readr::read_csv) have the opposite default; they don't transform the column names to make them legal R symbols unless you explicitly request it.

    0 讨论(0)
  • 2020-12-08 16:45
    s_data <- read.csv( file=f_name , check.names=FALSE)
    
    0 讨论(0)
提交回复
热议问题