user9022601
user9022601

Reputation: 19

Unlist character column to data frame in R

I have the following table "Table" with one column. I need to obtain the "output" table below.

Table:

PLSS
S24-T27S-R16E
S28-T27S-R17E
S21-T27S-R17E
S5-T28S-R16E

output:

Sec   Town   Range
S24   T27S   R16E
S28   T27S   R17E
S21   T27S   R17E
S5    T28S   R16E

I have the following code.

test <- as.character(strsplit(Table$PLSS, "-"))
test <- data.frame(test)

test
c("S24","T27S","R16E")
c("S28","T27S","R17E")
c("S21","T27S","R17E")
c("S5","T28S","R16E")

How can I convert the "test" to achieve the "output"?

Upvotes: 2

Views: 416

Answers (2)

storaged
storaged

Reputation: 1847

I will share with another idea. Instead of

test <- as.character(strsplit(tbl$PLS, "-"))
test <- data.frame(unlist(test))

Try this

test <- data.frame(matrix(unlist(strsplit(tbl$PLS, "-")), 4, 3, byrow = T))
colnames(test) <- c('Sec', 'Town', 'Range')

Upvotes: 0

akrun
akrun

Reputation: 887098

We can do a base R option with read.table

read.table(text=tbl$PLSS, sep="-", header = FALSE, 
    stringsAsFactors = FALSE, col.names = c('Sec', 'Town', 'Range'))
#   Sec Town Range
#1 S24 T27S  R16E
#2 S28 T27S  R17E
#3 S21 T27S  R17E
#4  S5 T28S  R16E

Upvotes: 1

Related Questions