【问题标题】:Convert the following into a loop function将以下内容转换为循环函数
【发布时间】:2017-12-07 14:37:30
【问题描述】:

我有一个小数据集,我正在尝试使用 grepl 函数对 data.frame 进行子集化。

我有;

year_list <- list("2013", "2014", "2015", "2016", "2017")

test.2013 <- subset(searches[, 1:2], grepl(year_list[1], searches$date))
test.2014 <- subset(searches[, 1:2], grepl(year_list[2], searches$date))
test.2015 <- subset(searches[, 1:2], grepl(year_list[3], searches$date))
test.2016 <- subset(searches[, 1:2], grepl(year_list[4], searches$date))
test.2017 <- subset(searches[, 1:2], grepl(year_list[5], searches$date))

我正在尝试创建一个循环,以便将第 1 列到第 2 列(date 列和 hits 列)子集化为新的 data.frame

我正在尝试使用year_lists 中的date,将grepl 函数应用于searches data.frame 中的date 列,并将这些值返回到新的data.frame,但使用循环函数或更少的函数比我现在的重复。

数据框

         date hits         keyword   geo gprop category
1: 2013-01-06   23  Price world   web        0
2: 2013-01-13   23  Price world   web        0
3: 2013-01-20   40  Price world   web        0
4: 2013-01-27   25  Price world   web        0
5: 2013-02-03   21  Price world   web        0
6: 2013-02-10   19  Price world   web        0

【问题讨论】:

  • 您正在使用 data.table-object。
  • library("lubridate"); searches[, Year:=year(as.Date(date))] ... 现在您可以使用split(searches, searches[, Year]) ... 或者最终您想使用data.tableby= 参数进行进一步计算。

标签: r


【解决方案1】:

如果我的理解是正确的,您希望根据日期列中的条目将data.frame 拆分为多个data.framess,那么您可以考虑以下解决方案,它会生成所需data.frame 的列表使用split 的子集。我使用了你的数据(不是data.table)并引入了代表额外一年的两条线。我希望我的理解是正确的。

df <- read.table(text = "
date hits         keyword   geo gprop category
2013-01-06   23  Price world   web        0
2013-01-13   23  Price world   web        0
2013-01-20   40  Price world   web        0
2013-01-27   25  Price world   web        0
2013-02-03   21  Price world   web        0
2013-02-10   19  Price world   web        0
2014-02-03   21  Price world   web        0
2014-02-10   19  Price world   web        0
", header = T, stringsAsFactors = F)

#extract only the four first digits from date column
#to generate splitting groups
df_split <- split(df[, c("date", "hits")], gsub("(\\d{4})(.*$)", "\\1", df$date))

df_split
# $`2013`
#       date    hits
# 1 2013-01-06   23
# 2 2013-01-13   23
# 3 2013-01-20   40
# 4 2013-01-27   25
# 5 2013-02-03   21
# 6 2013-02-10   19
# 
# $`2014`
#       date    hits
# 7 2014-02-03   21
# 8 2014-02-10   19

【讨论】:

  • 不完全是,我按照你的方法,但是一旦拆分就无法将它放入data.frame中
  • 我一直在从事以下工作 func &lt;- for(i in 1:5){ df &lt;- subset(searches[, 1:3], grepl(year_list[i], searches$date)) print(df) } data &lt;- data.frame(df) - 这只是去年的“保存”,所以我有一个新的 data.frame 但只有 2017 年。我正在尝试创建数据.frame 2013 - 2017 年所有年份
  • 为什么需要您的data.frames 作为单独的变量?您可以在列表结构中访问它们中的每一个,例如df_split[["2013"]]。如果您坚持创建单独的变量,我可以在this answer 的基础上为您提供解决方案,不过,这里也强调不应遵循这种方法。关于你的循环,在你的 for 循环中,你会在每次迭代中覆盖你的 df,因此,只有最后一个在循环中存活。
  • 如果这能解决您的问题或您需要额外的支持,请告诉我。
  • 不,谢谢,这确实解决了我的问题,我想在一个干净的循环函数中完成它,但稍微清理一下,我得到了相同的整体效果,谢谢!
猜你喜欢
  • 2017-02-20
  • 2020-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 2020-01-22
  • 2013-05-31
相关资源
最近更新 更多