I've got this structure tbl
that has the form:
> tbl
a_1 a_2 a_3
[1,] "L" "14" "L"
[2,] "L" "62" "D"
[3,] "H" "0" "L"
this is a matrix, actually:
> class(tbl)
[1] "matrix"
but when I attempt to change this into a data.frame
, all the entries of the df are displaying only the datatype, like so:
>as.data.frame(tbl, nrow = length(tbl[,1]), ncol = 3, byrow = TRUE)
a_1 a_2 a_3
<list> <list> <list>
<chr[1]> <chr[1]> <chr[1]>
<chr[1]> <chr[1]> <chr[1]>
<chr[1]> <chr[1]> <chr[1]>
I have tried a number of options but none of them seem to work including:
data.frame(rows=rownames(tbl)[row(tbl)],vars=colnames(tbl)[col(tbl)], values=c(tbl))
but I receive an error when I try to use it. I would like the resulting data.frame
to take the form:
a_1 a_2 a_3
<char> <chr> <char>
"L" "14" "L"
"L" "62" "D"
"H" "0" "L"
I looked for similar q's but couldn't find anyone who had this same issue. Any advice would be a great help!
dput(tbl)
structure(list("L", "L", "H", "14", "62", "0", "L", "D", "L"), .Dim = c(3L, 3L), .Dimnames = list(NULL, c("a_1", "a_2", "a_3")))
str(tbl)
List of 9
$ : chr "L"
$ : chr "L"
$ : chr "H"
$ : chr "14"
$ : chr "62"
$ : chr "0"
$ : chr "L"
$ : chr "D"
$ : chr "L"
- attr(*, "dim")= int [1:2] 3 3
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr [1:3] "a_1" "a_2" "a_3"
Try this one-liner:
as.data.frame(apply(tbl, 2, unlist))
or this:
tbl2 <- unlist(tbl)
attributes(tbl2) <- attributes(tbl)
DF <- as.data.frame(tbl2)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.