如何循环变量列表以使用循环或应用函数简化代码?

时间:2019-06-16 21:39:42

标签: r loops apply

我想使代码更简单,但我不知道在这种情况下如何使用“循环”。

Sample_Pollution_and_wind_monthly<-mutate(Sample_Pollution_and_wind_monthly,rounded_angle1=angle1)
Sample_Pollution_and_wind_monthly$rounded_angle1<-
  cut(Sample_Pollution_and_wind_monthly$rounded_angle1, breaks = c(0,22.5,67.5,112.5,157.5,202.5,247.5,292.5,337.5,360), right = TRUE, labels=c(0,45,90,135,180,225,270,315,360) )

Sample_Pollution_and_wind_monthly<-mutate(Sample_Pollution_and_wind_monthly,rounded_angle2=angle2)
Sample_Pollution_and_wind_monthly$rounded_angle2<-
  cut(Sample_Pollution_and_wind_monthly$rounded_angle2, breaks = c(0,22.5,67.5,112.5,157.5,202.5,247.5,292.5,337.5,360), right = TRUE, labels=c(0,45,90,135,180,225,270,315,360) )
...
...

(全部粘贴31次)  我只是将rounded_angle从1更改为31,而不更改整体功能。因为我不想重复31次,而且我想简单,您可以使用“循环”功能帮助我解决此问题吗?如果您对其他功能有更好的了解,也可以!

这是我在R中的循环代码(不起作用??)

for(x in 1:31) {
  Sample_Pollution_and_wind_monthly<-mutate(Sample_Pollution_and_wind_monthly,rounded_anglex=anglex)
  Sample_Pollution_and_wind_monthly$rounded_anglex<-
    cut(Sample_Pollution_and_wind_monthly$rounded_anglex, breaks = c(0,22.5,67.5,112.5,157.5,202.5,247.5,292.5,337.5,360), right = TRUE, labels=c(0,45,90,135,180,225,270,315,360) )

}

0 个答案:

没有答案