R Key Value Pair like Hastable

R Key Value Pair like Hastable

我是R编程的新手,你能帮忙解决两个场景吗?

  1. 如何自动化 n 个属性和值,例如 Attribute_1_Name、Attribute_1_Value...、Attribute_n_Name、Attribute_n_Value 并获得最终结果如下图?

    result = cbind.data.frame(
    PFA_Unique_Identifier,
    Fund_Unique_Identifier,
    VaR_Type,
    
    Attribute_1_Name,
    Attribute_1_Value,
    Attribute_2_Name,
    Attribute_2_Value, .............., Attribute_n_Name, Attribute_n_Value, varValueRaw )
    
  2. 如何创建 name/value 对的散列 table 并在 R 中自动执行以下代码。

    if (attributeCount == 0)
      {
        Attribute_1_Value = Attribute_1_Name = NA
        Attribute_2_Value = Attribute_2_Name = NA
      }
      else if (attributeCount == 1)
      {
        Attribute_1_Name = rep(attributeNames,n)
        Attribute_1_Value = attributeFilter
        Attribute_2_Value = Attribute_2_Name = NA
      }
      else if (attributeCount == 2)
      {
        Attribute_1_Name = rep(attributeNames[1],n)
        Attribute_1_Value = attributeFilter[,1]
        Attribute_2_Name = rep(attributeNames[2],n)
        Attribute_2_Value = attributeFilter[,2]
      }
      else
      {
        stop("It has not been implemented for attributes filter more than 2")
      }
    

很难理解你在问什么,但我认为你在寻找FAQ 7.21

该答案最重要的部分是最后几句话,其中说将事物放入列表是最简单的。如果您确实需要对 keys/names 进行哈希处理,那么您可以使用环境而不是列表,界面几乎相同,但环境使用哈希,最后我记得列表进行线性查找(您可能不会注意到除非您的列表或环境中有几千个对象,否则会有区别。

您只是想创建向量还是字符串? (记住列表不同于向量)。

如果是这样,这是一种方法:

n <- 3
outstring <- c(
  "PFA_Unique_Identifier", "Fund_Unique_Identifier", "VaR_Type",
  rbind(
    sprintf("Attribute_%d_Name", seq_len(n)),
    sprintf("Attribute_%d_Value", seq_len(n))
  ),
  "varValueRaw"
)

outstring

如果您希望将其作为单个字符串,请执行以下操作:

paste(outstring, collapse=", ")