在一个语句中创建一个带名称的数值向量?

我试图将函数参数的默认值设置为命名的数值。有没有办法在一个语句中创建一个语句?我查过了?数字和?但似乎并非如此。也许我可以转换/强制一个矩阵或 data.frame,并在一个语句中得到相同的结果?先说清楚,我试图一次性做到以下几点:

test = c( 1 , 2 )
names( test ) = c( "A" , "B" )
51404 次浏览

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

How about:

 c(A = 1, B = 2)
A B
1 2

...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"

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

test <- setNames(c(1, 2), c("A", "B"))

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

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