【问题标题】:Low efficiency when I loop in dataframe R当我在数据帧 R 中循环时效率低
【发布时间】:2016-06-20 22:26:47
【问题描述】:

我使用以下代码将月份名称映射到数字,与其他没有 for 循环的数据帧计算相比,我发现它的效率较低。

Sys.time()
head(df[,4])
for (i in 1:nrow(df)){
  df$monthnum[i]<-match(tolower(as.character(df[i,4])), tolower(month.name))
}
Sys.time()

我得到这样的输出:

    > Sys.time()
[1] "2016-03-07 19:20:53 CST"
> dim(df)
[1] 229464      6
> head(df[,4])
[1] January January January January January January
Levels: April August December February January July June March May November October September
> for (i in 1:nrow(df)){
+   df$monthnum[i]<-match(tolower(as.character(df[i,4])), tolower(month.name))
+ }
> Sys.time()
[1] "2016-03-07 19:23:23 CST"

任何人都可以在数据框中使用 for 循环的逻辑。任何信息将不胜感激。

【问题讨论】:

  • 也许this 有助于解释为什么循环使用数据帧效率如此之低。你的代码只是df$monthnum &lt;- match(tolower(as.character(df[,4], tolower(month.name))

标签: r loops for-loop


【解决方案1】:

使用sapply 函数。 首先,创建你的函数:

my_function = function(my_month){
  match(tolower(as.character(my_month)), tolower(month.name))
}

然后使用sapply

sapply(df[,4],my_function)

【讨论】:

  • 这很有帮助,只需几秒钟即可完成,数据帧中的循环是否增加了复杂性。
  • 对不起,我没有得到你评论的第二部分。如果这解决了您的问题,您可以单击勾号将其选为答案。
猜你喜欢
  • 2011-03-08
  • 2021-03-14
  • 2019-07-29
  • 2016-05-18
  • 2020-10-10
  • 1970-01-01
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多