如何在R语言中使用表达式作为c()函数的键?
在R中动态生成
c()函数的键名方法 你遇到的问题是R的语法限制导致的:在c()的key = value参数形式里,key必须是字面量(要么是合法的标识符,要么是引号包裹的字符串常量),没法直接用动态计算的表达式生成。不过有两种简单的解决办法:
方法1:使用setNames()函数
这是最简洁的方式,先准备好值向量和动态生成的键名向量,再用setNames()把两者绑定:
# 先生成键名和值 keys <- c( paste("first", "second", "third"), paste("or", "some", "other", "strings"), "XYZ" ) values <- c("foo", "someothervalue", "baz") # 绑定名称 result <- setNames(values, keys)
也可以把代码合并成一行:
result <- setNames( c("foo", "someothervalue", "baz"), c(paste("first", "second", "third"), paste("or", "some", "other", "strings"), "XYZ") )
方法2:先创建无名称向量,再手动设置names属性
先创建普通向量,之后再给它赋值名称属性,效果和上面一致:
result <- c("foo", "someothervalue", "baz") names(result) <- c( paste("first", "second", "third"), paste("or", "some", "other", "strings"), "XYZ" )
两种方法最终都会得到你需要的带动态生成键名的向量,执行后result的输出为:
first second third or some other strings XYZ "foo" "someothervalue" "baz"
内容的提问来源于stack exchange,提问作者user3064538
相关产品推荐
相关产品推荐

