基于R中的2个以上条件进行分配,以重新分配矢量的数据值

时间:2022-02-08 22:58:55

I have rather large meteorological data sets that look something like:

我有相当大的气象数据集,如下所示:

year  month day hour min sec temp RH Rad 

I need to convert the day to the sequential day of year, e.g:

我需要将日期转换为一年中的连续日期,例如:

  • jan 1 is day 0
  • 1月是第0天
  • feb 1 is day 31
  • 1月31日是第31天
  • march 1 is day 59 (in non leap years)
  • 3月1日是第59天(非闰年)
  • April 1 is 90, etc.
  • 4月1日是90等

Data are stored in a data frame, say met_dat, with met_dat$year, met_dat$day, etc.

数据存储在数据框中,比如met_dat,其中包含met_dat $ year,met_dat $ day等。

I'd like to assign the yd based on the month, i.e.,

我想根据月份分配yd,即

if met_dat$month==0, /*this is the code for january*/
then 
met_dat$yd<-met_dat$day,

else if met_dat$month==1, /*this is the code for february*/
then
met_dat$yd<-met_dat$day+30

else if met_dat$month==2,
then
met_dat$yd<-met_dat$day+58

etc, for the remaining months.

I've tried nesting ifelse statements as:

我已经尝试将ifelse语句嵌套为:

met_dat$yd<-ifelse( (met_dat$month==0),met_dat$yd<-met_dat$day,
           (ifelse( (met_dat$month==1), met_dat$yd<-met_dat$day+30,
              (ifelse( (met_dat$month==2), met_dat$yd<-met_dat$day+58, NA) )))

My real code has all 12 months, but 12 or three, this doesn't work...it assigns incorrect values for met_dat$yd, sometimes near correct, but never correct for all months.

我的真实代码有12个月,但有12或3个,这不起作用...它为met_dat $ yd指定了不正确的值,有时接近正确,但永远不会纠正所有月份。

Any suggestions?

有什么建议么?

1 个解决方案

#1


1  

You can convert your data to Date using as.Date, thus turning it into an integer representation. Then simply subtract an epoch (reference) date from each value. Like this:

您可以使用as.Date将数据转换为Date,从而将其转换为整数表示形式。然后简单地从每个值中减去一个纪元(参考)日期。喜欢这个:

x <- data.frame(
  year = 2012,
  month = c("Jan", "Jan", "Feb", "Mar", "Apr", "Apr"),
  day = c(1, 2, 1, 1, 1, 2)
)

xx <- with(x, as.Date(paste(year, month, day, sep="-"), format="%Y-%b-%d"))

xx
[1] "2012-01-01" "2012-01-02" "2012-02-01" "2012-03-01" "2012-04-01" "2012-04-02"

xx - as.Date("2012-01-01")
Time differences in days
[1]  0  1 31 60 91 92

#1


1  

You can convert your data to Date using as.Date, thus turning it into an integer representation. Then simply subtract an epoch (reference) date from each value. Like this:

您可以使用as.Date将数据转换为Date,从而将其转换为整数表示形式。然后简单地从每个值中减去一个纪元(参考)日期。喜欢这个:

x <- data.frame(
  year = 2012,
  month = c("Jan", "Jan", "Feb", "Mar", "Apr", "Apr"),
  day = c(1, 2, 1, 1, 1, 2)
)

xx <- with(x, as.Date(paste(year, month, day, sep="-"), format="%Y-%b-%d"))

xx
[1] "2012-01-01" "2012-01-02" "2012-02-01" "2012-03-01" "2012-04-01" "2012-04-02"

xx - as.Date("2012-01-01")
Time differences in days
[1]  0  1 31 60 91 92