2016-08-04 51 views
0

我試圖在R中編寫一個將輸入信息映射到輸出但將輸入保留在同一數據框中的函數。我有一個我寫的函數,它會接受輸入併爲單個值提供正確的輸出,但是我缺乏R知識來知道如何重寫這個,因此我可以傳入一個向量。R - 如何將一個新列添加到另一列的計算結果的數據框中

我想在一個框架中傳遞它,並向數據框添加一個新列。下面的實施例的代碼:

d <- data.frame(Type=c("_Swap_","Nothing","CAP", "FLOOR", "FLOOR", "BLAH", "Digital", "Something!")) 

d$newType= createTags(d$Type) 

createTags = function(Type){ 
    map = data.frame(input=c("Swap","Note","Option", "Floor", "FLOOR", "CAP", "Digital", "Bond"), 
        output=c("Swap","Note","Option", "CapFloor", "CapFloor", "CapFloor", "CapFloor", "Bond")) 

    tag="Unknown" 

    print(length(Type)) 

    for (j in 1:NROW(map)) {  
    input = map[j,]$input 
    output = map[j,]$output 

    ifelse (grepl(toupper(input), toupper(Type))){ 
     tag = output 
    }  
    } 

    return(tag) 
} 

所以在輸出我想d有兩列,一種是原始的類型,然後在端部應該有稱爲NEWTYPE第二列。

回答

0

我結束了這個很多玩耍。感謝馬克·蒂姆斯的幫助,但我意識到我需要使用grepl以確保我能涵蓋所有的情況下

SRTLondon <- 
    data.frame(Type=c("_Swap_","Nothing","CAP", "FLOOR", "FLOOR", "BLAH", "Digital", "Something!")) 

createTags = function(Type){ 
    #browser() 
    map = data.frame(input=c("Swap","Note","Option", "Floor", "FLOOR", "CAP", "Digital", "Bond"), 
       output=c("Swap","Note","Option", "CapFloor", "CapFloor", "CapFloor", "CapFloor", "Bond"),stringsAsFactors = F) 

    work = data.frame(x=toupper(Type),stringsAsFactors = F) 
    work$tag="NA" 

    for (i in 1:NROW(work)) { 
    check = work$x[i] 

    for (k in 1:nrow(map)){ 
     input = map[k,'input'] 
     output = map[k,'output'] 

     if(grepl(toupper(input),check)) 
     { 
     work$tag[i]=output 
     break 
     } 

    } 

    } 
    return(work$tag) 
} 

SRTLondon $ type.tags = createTags(SRTLondon $型)

0

可以使用switch函數的輸入映射到輸出:

# Create sample data 
d <- data.frame(
    type = c("_Swap_","Nothing","CAP", "FLOOR", "FLOOR", "BLAH", "Digital", "Something!") 
) 

# Use the switch function to map inputs to outputs 
create_tags <- function(type) { 
    type <- gsub("[[:punct:]]", "", tolower(type)) # standardize the letter case and remove punctuation 
    switch(
    type, 
    "swap" = "Swap", 
    "note" = "Note", 
    "option" = "Option", 
    "floor" = "CapFloor", 
    "cap"  = "CapFloor", 
    "digital" = "CapFloor", 
    "bond" = "Bond", 
    "Unknown" 
) 
} 

# Switch isn't vectorized so we have to sapply our create_tags function onto d$type 
d$new_type <- sapply(d$type, create_tags) 
+0

謝謝!我不知道交換機或sapply功能。更多學習! – David

相關問題