最快的实现方式

时间:2017-02-16 20:29:09

标签: r performance dataframe which

我确信除了在for循环中使用which()语句之外,还有一种优雅而快速的方法来填充数据框列...

colors = (
    "#D53E4F" "#FC8D59" "#FEE08B" 
    "#FFFFBF" "#E6F598" "#99D594" "#3288BD" 
)
n = 6277
wxData = data.frame(
    x = numeric(n - 1), 
    y = numeric(n - 1), 
    z = numeric(n - 1), 
    c = character(n - 1), 
    stringsAsFactors = FALSE 
)
for (j in 1 : n-1) {
    wxData$x[j]     = xCoord[[1]][j]  #"data.frame"
    wxData$y[j]     = yCoord[[1]][j]  #"data.frame"
    wxData$z[j]     = dbz[[1]][j]     #"data.frame"
    colorIndx      = which(wxData$z[j] == colorRanges) 
    wxData$c[j] = colors[colorIndx]  
}

如果以前曾被问过,请道歉,但我确实看了。

1 个答案:

答案 0 :(得分:1)

通常,如果提供的代码不可执行,则循环遍历

which( values[j] == array ) 

可以用一行没有循环替换

match(values, array)

例如:

values = c('a','a','b','c','b','a')
array = c('a','b','c')
match(values, array)

# 1 1 2 3 2 1