【问题标题】:sapply function in R is not giving me the desired resultR中的sapply函数没有给我想要的结果
【发布时间】:2015-02-23 03:10:06
【问题描述】:

我正在尝试使用 sapply 而不是“for”循环,但我没有得到我期望的结果,我已经测试了每一行分隔并且代码正在工作,但是当我使用 @987654323 @ 不是。我正在寻找一些可能出错的提示:

event <- c('Astronomical Low Tide', 'Avalanche', 'Blizzard', 'Coastal Flood', 
           'Cold/Wind Chill', 'Debris Flow', 'Dense Fog', 'Dense Smoke', 'Drought',
           'Dust Devil', 'Dust Storm','Excessive Heat', 'Extreme Cold/Wind Chill',
           'Flash Flood', 'Flood', 'Frost/Freeze', 'Funnel Cloud', 'Freezing Fog',
           'Hail', 'Heat', 'Heavy Rain', 'Heavy Snow', 'High Surf', 'High Wind',
           'Hurricane/Typhoon', 'Ice Storm', 'Lake/Effect Snow', 'Lakeshore Flood',
           'Lightning', 'Marine Hail', 'Marine High Wind', 'Marine Strong Wind',
           'Marine Thunderstorm Wind', 'Rip Current', 'Seiche', 'Sleet',
           'Storm Surge/Tide', 'Strong Wind', 'Thunderstorm Wind', 'Tornado',
           'Tropical Depression', 'Tropical Storm', 'Tsunami', 'Volcanic Ash',
           'Waterspout', 'Wildfire', 'Winter Storm', 'Winter Weather')

replace <- function(dt, x, col) {
  idx <- grep(paste('(?i)', event[x], sep = ''), dt[, col])
  dt[idx, col] <- event[x]
}

sapply(1:length(event), function(x) replace(stormdata, x, 8))

基本上,我要做的是使用event 变量上的每个值作为自定义replace 函数中grep 函数的模式,然后我得到匹配行的索引我的模式并将它们存储在idx 变量中。之后,我想将数据框中与idx 值对应的行替换为event 变量中包含的值。

我正在尝试使用sapply 函数创建一个循环以使用event 变量上的每个值,所以我想要一个循环48 次在其上查找数据帧stormdata 中的每个模式第 8 列并替换它们。但是我的代码什么都不做,运行后数据保持不变,没有替换。当我在没有sapply 的情况下单独运行每一行时,它可以工作。

我到处寻找,我找不到为什么不起作用。帮助。

【问题讨论】:

  • 如果您还包括一个示例 stormdata 对象来制作您的示例 reproducible,将会更有帮助。一般来说,使用函数式编程语言,您不希望您的函数有副作用。如果你想改变一个对象,你的函数应该返回一个新的、更新的对象,而不是试图编辑一个现有的对象。当您在函数中编辑变量时,这些更改通常仅在该函数内部可见,并在函数终止时消失。
  • 查看sapply(.) 调用的唯一方法是将结果分配给符号。在您早期在 R 中将其分配回stormdata 是相当危险的,但为什么不将其分配给stormtemp 然后再查看呢?

标签: regex r sapply


【解决方案1】:

尝试在您的函数中使用全局赋值,例如stormdata[idx, col] &lt;&lt;- event[x]。不干净,但可能会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2020-08-06
    • 2018-12-14
    • 2021-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多