2016-01-13 24 views
0

我是R編程新手,能否請您幫忙解決兩種情況?R關鍵值對像Hastable

  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. 如何創建名稱/值對的哈希表和自動化下面的代碼在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") 
        } 
    

回答

1

這是很難明白你問什麼,但我認爲你正在尋找FAQ 7.21

答案中最重要的部分是最後幾句話,它表示將事情列入清單最簡單。如果你真的需要把鍵/名字散列化,那麼你可以使用一個環境而不是一個列表,界面幾乎是相同的,但是環境使用散列,最後我記得列表做了一個線性查找(你可能不會注意到一個區別除非在列表或環境中有幾千個對象)。

你只是想創建一個向量或字符串? (記住一個列表與矢量不同)。

如果是這樣,這裏是一個辦法:

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=", ") 
+0

感謝。讓我再澄清一下我在找什麼。我如何動態獲取這個列表? 「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」 – Partha

+0

@Partha,我已經加入上面的例子,是你想要的嗎? –

+0

Greg - 很完美。這就是我一直在尋找的。還有一個問題給你。當我嘗試在cbind.data.frame中使用該字符串時,出現錯誤。你知道我該如何修復它嗎?這是錯誤:「data.frame中的錯誤(...,check.names = FALSE): 參數意味着不同的行數:1,2,0」 ttibuteColumns < - paste(outstring,collapse =「,」 ) result = cbind.data.frame(attibuteColumns) – Partha