Create a numeric vector with names in one statement?

前端 未结 6 1908
无人及你
无人及你 2020-12-01 09:52

I\'m trying to set the default value for a function parameter to a named numeric. Is there a way to create one in a single statement? I checked ?numeric and ?vector but it

相关标签:
6条回答
  • 2020-12-01 10:33

    How about:

     c(A = 1, B = 2)
    A B 
    1 2 
    
    0 讨论(0)
  • 2020-12-01 10:33

    To expand upon @joran's answer (I couldn't get this to format correctly as a comment): If the named vector is assigned to a variable, the values of A and B are accessed via subsetting using the [ function. Use the names to subset the vector the same way you might use the index number to subset:

    my_vector = c(A = 1, B = 2)    
    my_vector["A"] # subset by name  
    # A  
    # 1  
    my_vector[1] # subset by index  
    # A  
    # 1  
    
    0 讨论(0)
  • 2020-12-01 10:36

    ...as a side note, the structure function allows you to set ALL attributes, not just names:

    structure(1:10, names=letters[1:10], foo="bar", class="myclass")
    

    Which would produce

     a  b  c  d  e  f  g  h  i  j 
     1  2  3  4  5  6  7  8  9 10 
    attr(,"foo")
    [1] "bar"
    attr(,"class")
    [1] "myclass"
    
    0 讨论(0)
  • 2020-12-01 10:39

    magrittr offers a nice and clean solution.

    result = c(1,2) %>% set_names(c("A", "B"))
    print(result)
    A B 
    1 2
    

    You can also use it to transform data.frames into vectors.

    df = data.frame(value=1:10, label=letters[1:10])
    vec = extract2(df, 'value') %>% set_names(df$label)
    vec
     a  b  c  d  e  f  g  h  i  j 
     1  2  3  4  5  6  7  8  9 10
    df
        value label
     1      1     a
     2      2     b
     3      3     c
     4      4     d
     5      5     e
     6      6     f
     7      7     g
     8      8     h
     9      9     i
     10    10     j
    
    0 讨论(0)
  • 2020-12-01 10:48

    The convention for naming vector elements is the same as with lists:

    newfunc <- function(A=1, B=2) { body}  # the parameters are an 'alist' with two items
    

    If instead you wanted this to be a parameter that was a named vector (the sort of function that would handle arguments supplied by apply):

    newfunc <- function(params =c(A=1, B=2) ) { body} # a vector wtih two elements
    

    If instead you wanted this to be a parameter that was a named list:

    newfunc <- function(params =list(A=1, B=2) ) { body} 
        # a single parameter (with two elements in a list structure
    
    0 讨论(0)
  • 2020-12-01 10:51

    The setNames() function is made for this purpose. As described in Advanced R and ?setNames:

    test <- setNames(c(1, 2), c("A", "B"))
    
    0 讨论(0)
提交回复
热议问题