Wafa El Maizi
Wafa El Maizi

Reputation: 33

R: Gathering multiple tables in one data frame

I would like to extract single table from a text file with multiple tables of the same data,I want to get a table with 3 colomns:Nscore, Cases, Value and contain the rows of all the 3 tables .

# dput(neuroticism)
c("<br>     Nscore Cases Value         Nscore Cases Value         Nscore Cases Value", 
"<br>     12      1    -3.46436      29     60    -0.67825      46     67    1.02119", 
"<br>     13      1    -3.15735      30     61    -0.58016      47     27    1.13281", 
"<br>     14      7    -2.75696      31     87    -0.46725      48     49    1.23461", 
"<br>     15      4    -2.52197      32     78    -0.34799      49     40    1.37297", 
"<br>     16      3    -2.42317      33     68    -0.24649      50     24    1.49158", 
"<br>     17      4    -2.34360      34     76    -0.14882      51     27    1.60383", 
"<br>     18     10    -2.21844      35     69    -0.05188      52     17    1.72012", 
"<br>     19     16    -2.05048      36     73     0.04257      53     20    1.83990", 
"<br>     20     24    -1.86962      37     67     0.13606      54     15    1.98437", 
"<br>     21     31    -1.69163      38     63     0.22393      55     11    2.12700", 
"<br>     22     26    -1.55078      39     66     0.31287      56     10    2.28554", 
"<br>     23     29    -1.43907      40     80     0.41667      57      6    2.46262", 
"<br>     24     35    -1.32828      41     61     0.52135      58      3    2.61139", 
"<br>     25     56    -1.19430      42     77     0.62967      59      5    2.82196", 
"<br>     26     57    -1.05308      43     49     0.73545      60      2    3.27393", 
"<br>     27     65    -0.92104      44     51     0.82562", 
"<br>     28     70    -0.79151      45     37     0.91093")

Upvotes: 1

Views: 526

Answers (1)

akrun
akrun

Reputation: 886948

We can use read.table after pasteing into a single string to create a data.frame

df1 <- read.table(text=paste(neuroticism, collapse="\n"), header = TRUE, fill = TRUE)

and then melt into 'long' format using data.table::melt

library(data.table)
melt(setDT(df1), measure = patterns("^Nscore", "^Cases", "^Value"), 
       value.name = c("Nscore", "Cases", "Value"))[, variable := NULL][!is.na(Nscore)]

Upvotes: 1

Related Questions