Search code examples
rlistvectordata-manipulationlist-manipulation

List to a vector with conditional logic


I have a list such as,

lst <- list(1, c(3, 4, 6), c(2, 5))

Every first element of this list has prime importance. You can think the numbers in the list positions. For example, there are 1 to 6 positions where position 1 is not combined with any other. Position 4 and 6 are combined with position 3 and position 5 is combined with position 2. Now I need to create a vector as,

W1 W2 W3 W4 W5 W6
W1 W2 W3 W3 W2 W3

This is a named vector. The name is the name of a position and the values are the position with which they are combined. This seems easy but is taking a lot of my time. Thank you in advance.


Solution

  • res <- character(length(unlist(lst)))
    names(res) <- paste0("W", seq_along(unlist(lst)))
    lapply(lst, function(x) res[x] <<- paste0("W", x[1]))
    res
    #   W1   W2   W3   W4   W5   W6 
    # "W1" "W2" "W3" "W3" "W2" "W3" 
    

    Edit

    Or maybe this is one of those cases where a for loop is better (and avoids <<-):

    res <- character(length(unlist(lst)))
    names(res) <- paste0("W", seq_along(unlist(lst)))
    for (x in lst) res[x] <- paste0("W", x[1])
    res
    #   W1   W2   W3   W4   W5   W6 
    # "W1" "W2" "W3" "W3" "W2" "W3"