Convert a Vector into a List, Each Element in the Vector as an Element in the List

R turn each element in a vector into a list of lists

you could use

lapply(vector,list)

Edit: for new desired output

sapply(vector,list)

Unpacking a vector into a list with each element of vector as separate elements in list

The solution is:

details = c(list(t=20,y="c"),scales)

How to turn a named vector into a named list, while grouping entries with the same name into one list element?

We can do this with splitting the vector by the names of the vector

tmp_n <- split(unname(tmp_v), names(tmp_v))
identical(tmp_n, tmp_l)
#[1] TRUE

Converting Vector into List

split is probably the most appropriate function for this sort of task:

split(par, rep(1:3,each=2) )

#$`1`
#[1] 0.5 0.7
#
#$`2`
#[1] 0.9 1.0
#
#$`3`
#[1] 1.8 1.5

How to convert a vector into a list in R?

You could use split()

split(vec, (seq_along(vec)-1) %/% 2)

Or if you wanted to go to a matrix first, then

library(magrittr)   # for %>%
matrix(vec, nrow=2) %>% split(., col(.))

How to split a vector into a particular list?

x = c(102, 104, 89, 89, 76)

splitter <- function(v) {
n <- length(x)
z <- NULL
z[[1]] <- NA
for(i in 2:n-1) {
z[[i+1]] <- x[1:i]
}
z
}

splitter(x)

convert a vector to a list

Like this?

R> kn <- c("1", "a", "b")
R> nl <- vector(mode="list", length=length(kn)-1)
R> names(nl) <- kn[-1]
R> nl <- lapply(nl, function(x) kn[1])
R> nl
$a
[1] "1"

$b
[1] "1"

R>

With kudos to Gavin for spotting an earlier
error.

create a list with named elements from a vector in R

You can use as.list with lapply to get exact same output :

lapply(as.list(myList), function(x) setNames(as.list(x), 'value'))

#[[1]]
#[[1]]$value
#[1] 0.08986225

#[[2]]
#[[2]]$value
#[1] 0.1127987

#[[3]]
#[[3]]$value
#[1] 0.1182074

#[[4]]
#[[4]]$value
#[1] 0.1138769

#...
#...

How to create a function that transforms each element of the list that's not numeric into as.numeric?

Here you go:

library(purrr)

list <- list(
z = c(a = 30000, b = 12, c = 600, d = 10),
x = c(a = 30000, b = 12, c = list(list(1600, 1400, 1400, 1200)), d = list(list(10,10))))

list <- list %>% modify_depth(2, as.numeric)
list

Output:

> list
$z
a b c d
30000 12 600 10

$x
$x$a
[1] 30000

$x$b
[1] 12

$x$c
[1] 1600 1400 1400 1200

$x$d
[1] 10 10


Related Topics



Leave a reply



Submit