Reputation: 301
I have a list (or dictionary) like this:
df <- list(`digits/trainingDigits/0_0.txt` = c(0, 1, 1, 0), `digits/trainingDigits/0_1.txt` = c(0, 1, 0, 0), `digits/trainingDigits/0_10.txt` = c(0, 0, 1, 0))
I would like to convert it to a list like:
df <- list(c(0, 1, 1, 0), c(0, 1, 0, 0), c(0, 0, 1, 0))
Somehow removing the text before the "=". I am quite new to r, I assume it's like a Python dictionary with keys and values. In this case, I would like to have the list of values.
So at the end I would have this:
df2 <- list(c(0, 1, 1, 0), c(0, 1, 0, 0), c(0, 0, 1, 0))
df2 <- as.data.frame(df2)
t(df2)
With this outcome:
Upvotes: 1
Views: 1534
Reputation: 78792
dat <- list(
`digits/trainingDigits/0_0.txt` = c(0, 1, 1, 0),
`digits/trainingDigits/0_1.txt` = c(0, 1, 0, 0),
`digits/trainingDigits/0_10.txt` = c(0, 0, 1, 0)
)
The above is a named list. Let's remove the names:
str(unname(dat))
## List of 3
## $ : num [1:4] 0 1 1 0
## $ : num [1:4] 0 1 0 0
## $ : num [1:4] 0 0 1 0
Now the above is an unnamed list. We can turn that into a numeric matrix:
do.call(rbind, unname(dat))
## [,1] [,2] [,3] [,4]
## [1,] 0 1 1 0
## [2,] 0 1 0 0
## [3,] 0 0 1 0
Then turn that into a data frame:
as.data.frame(do.call(rbind, unname(dat)))
## V1 V2 V3 V4
## 1 0 1 1 0
## 2 0 1 0 0
## 3 0 0 1 0
Upvotes: 3