Curious
Curious

Reputation: 549

How to convert data in text file to data frame?

I have data in a text file where each row have one value and total number of columns is 4 (in this case first four rows = first column in data frame):

#this is the raw data:
test1
100
95
red
test2
50
70
blue
test3
66
88.8
yellow

Desired output:

enter image description here

Upvotes: 0

Views: 109

Answers (2)

Johnny
Johnny

Reputation: 771

You could achieve this by doing the following:

test.file <- read.delim(file.choose(), sep = "\n", header = FALSE)
as.data.frame(matrix(test.file$V1, ncol = 4, byrow = T))

If you are using RStudio file.choose() will open a dialog that allows you to select your text file.

Upvotes: 0

nghauran
nghauran

Reputation: 6768

Here is one option:

df <- read.table(text = "test1
                 100
                 95
                 red
                 test2
                 50
                 70
                 blue
                 test3
                 66
                 88.8
                 yellow", header = FALSE)
as.data.frame(matrix(df$V1, ncol = 4, byrow = TRUE))
# output
     V1  V2   V3     V4
1 test1 100   95    red
2 test2  50   70   blue
3 test3  66 88.8 yellow

Upvotes: 1

Related Questions