Geneva
Geneva

Reputation: 9

Create a vector from a .txt data file in R

It's my first time here on stackoverflow so be indulgent with me in the beginning, I'm not fully aware of all the rules here. :) My first topic would concern vector creation from a .txt data file in R.

I have this kind of data:

Piece   Mes.1   Mes.2   Mes.3   Mes.1.2 Mes.2.2 Mes.3.2

1   50  49  50  50  48  51

2   52  52  51  51  51  51

3   53  50  50  54  52  51

4   49  51  50  48  50  51

and I would like to create a vector directly from the .txt file without having to rewrite each number. The vector that I would like to create would include all the data line by line:

x<-c(50,49,50,50,48,51,52,52,51,51,51,51,53,50,50,54,52,51,49,51,50,
     48,50,51,48,49,48,48,49,48,52,50,50,52,50,50,51,51,51,51,50,50,
     52,50,49,53,48,50,50,51,50,51,48,49,47,46,49,46,47,48)

The name of my data file in R is "data1" and have tried this below but it doesn't work:

y<-c(data1[1,2:7],data1[2,2:7],data1[3,2:7] 

and so on until 10, but it doesn't work.

You guys would be a great help if someone can provide a solution :) Thanks !

Upvotes: 1

Views: 4292

Answers (3)

Rui Barradas
Rui Barradas

Reputation: 76450

I believe that scan is the best way of doing it, it reads line by line and returns vectors, there is no need to convert to matrix, transpose and unlist.

Read in the first line to know how many columns are there in the table. Then read in the data directly into a vector and remove the extra, first column, elements.

n <- length(scan(file = "data.txt", nlines = 1L, what = character()))
y <- scan(file = "data.txt", skip = 1L)
y <- y[-seq(1, length(y), by = n)]
y

Now compare to the first 24 elements of the posted expected result.

identical(x[1:24], y)
#[1] TRUE

Upvotes: 2

Ashish Baid
Ashish Baid

Reputation: 533

Here's a 2 line solution to your problem

data1<-read.delim('data1.txt',header=TRUE,sep = " ")

your_dear_vector<-as.vector(unlist(t(as.matrix(data1[,-1]))))

Enjoy and keep posting!

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101628

You can try the code below

df <- read.table(file = "data.txt", header = T, stringsAsFactors = F)
x <- as.vector(t(as.matrix(df[-1])))

such that

> x
 [1] 50 49 50 50 48 51 52 52 51 51 51 51 53 50 50 54 52 51 49 51 50 48 50
[24] 51

DATA

df <- structure(list(Piece = 1:4, Mes.1 = c(50L, 52L, 53L, 49L), Mes.2 = c(49L, 
52L, 50L, 51L), Mes.3 = c(50L, 51L, 50L, 50L), Mes.1.2 = c(50L, 
51L, 54L, 48L), Mes.2.2 = c(48L, 51L, 52L, 50L), Mes.3.2 = c(51L, 
51L, 51L, 51L)), class = "data.frame", row.names = c(NA, -4L))

Upvotes: 2

Related Questions