djMohit
djMohit

Reputation: 171

Converting text file into dataframe in R

I am trying to convert text file data in R. The dataset looks like this

RXID- 3233
OWN - NLM
AU  - HBGHB
AB  - good boy. 

RXID- 3234
OWN - NLM
AU  - HBGJI
AB  - bad boy. 

I referred converting multiple lines of text into a data frame and i did this

x<-read.delim("Test.txt", header = FALSE, sep = "-", strip.white = TRUE) #this is working well
cols<-levels(x[,'V1'])  #This is giving a null value 

I am not able to find out why this is coming NULL

The final output should look like this

RXID   OWN   AU    AB
3233   NLM   HBGHB   good boy
3234   NLM   HBGJI   bad boy

Upvotes: 1

Views: 728

Answers (1)

Edward
Edward

Reputation: 19514

I guess you are using R 4.0.0?

If you add "stringsAsFactors=TRUE" to your read.delim command, it should work.

x <- read.delim("Test.txt", header = FALSE, sep = "-", strip.white = TRUE,
                 stringsAsFactors=TRUE)

cols <- levels(x[,'V1']); cols
[1] "AB"   "AU"   "OWN"  "RXID"

d <- data.frame(sapply(cols, function(y) {x['V2'][x['V1']==y]}, USE.NAMES=TRUE))
d
        AB    AU OWN RXID
1 good boy HBGHB NLM 3233
2  bad boy HBGJI NLM 3234

The code you copied was written 10 years ago when the default value for stringsAsFactors was TRUE. In the current version of R (4.0.0), the default value was changed to FALSE, so anything that looks like a character will remain as a character (unless you manually change the value to TRUE in the command to read the data).

Upvotes: 2

Related Questions