简体   繁体   中英

R software, read.csv, multiple separators

Does anyone know a way to read a csv file in R with multiple separators?

a<-read.csv("C:/Users/User/Desktop/file.csv", sep=",", header=FALSE)

Here, I have the following dataset (txt/csv file) separated by commas and spaces:

5.006,84.698  
4.604,87.725  7.250,88.392  
6.668,91.556  
5.927,95.440  
4.953,99.695  7.387,100.489  
6.466,104.447  
5.599,107.548  
4.053,111.411  7.440,112.892  
6.096,116.417  
4.805,119.031  7.546,120.671  
6.149,123.793  
4.307,127.201  7.461,129.974  
5.493,132.853  7.641,135.393  

and I want it to be read as a table with four columns, like this:

72 5.006  84.698    NA      NA  
73 4.604  87.725 7.250  88.392  
74 6.668  91.556    NA      NA  
75 5.927  95.440    NA      NA  
76 4.953  99.695 7.387 100.489  
77 6.466 104.447    NA      NA  
78 5.599 107.548    NA      NA  
79 4.053 111.411 7.440 112.892  
80 6.096 116.417    NA      NA   
81 4.805 119.031 7.546 120.671  
82 6.149 123.793    NA      NA  
83 4.307 127.201 7.461 129.974  
84 5.493 132.853 7.641 135.393  

Do you know the possible way to read it that way in R?

We can try using readLines() to read each line as a string. Then, we can split on multiple separators and roll up into a data frame.

file <- "C:/Users/User/Desktop/file.csv"
txt <- readLines(file, sep = ""))
y <- strsplit(txt, "[, ]+")
z <- lapply(y,function(x){as.data.frame(t(as.numeric(x)))})
df <- do.call(rbind.fill, z)
df

You could open the file in any text editor (notepad or something similar) and make the separators common across the file. You can either replace ',' with spaces or vice-versa using Find and Replace all and save the file.

Once you do that you can use read.csv with this new separator.

a <- read.csv("C:/Users/User/Desktop/file.csv", sep= " ", header=FALSE, fill = TRUE)

One option is to use Excel. You can choose multiple separators (delimiters) during the import stage (Wizard step 2). Comma and space are one of the default choices but you can choose other characters too.

Then import the excel file using one of many user-contributed packages, for example, readxl , or save as text and use read.csv / read.table .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM