[英]What is the best way to create a new column based on two conditions?
我有60年的每日天气数据,想标记每个冬天(即1-60)。 由于冬季是跨年的,因此无法仅使用月份就可以ifelse
或编写简单的ifelse
语句。 嵌套的ifelse
语句指定60年中的每个月和年份似乎是不切实际的,是否有更好的方法来做到这一点?
这只是三年的例子。
month<-c(11,12,1,2,3,4,11,12,1,2,3,4,11,12,1,2,3,4)
year<-c(1950,1950,1951,1951,1951,1951,1951,1951,1952,1952,1952,1952,1952,1952,1953,1953,1953,1953)
df<-cbind(month,year)
df<-as.data.frame(df)
我希望将1950年11月至1951年4月之间的日期都标记为1。 1951年11月至1952年4月之间的日期标记为2,依此类推。
我希望最终的数据框看起来像这样:
month year winter
1 11 1950 1
2 12 1950 1
3 1 1951 1
4 2 1951 1
5 3 1951 1
6 4 1951 1
7 11 1951 2
8 12 1951 2
9 1 1952 2
10 2 1952 2
11 3 1952 2
12 4 1952 2
13 11 1952 3
14 12 1952 3
15 1 1953 3
16 2 1953 3
17 3 1953 3
18 4 1953 3
我有30多个气象站的60年每日数据,对采用这种简单方法有何想法?
像这样使用cumsum
:
transform(df, winter = cumsum(month == 11))
给予:
month year winter
1 11 1950 1
2 12 1950 1
3 1 1951 1
4 2 1951 1
5 3 1951 1
6 4 1951 1
7 11 1951 2
8 12 1951 2
9 1 1952 2
10 2 1952 2
11 3 1952 2
12 4 1952 2
13 11 1952 3
14 12 1952 3
15 1 1953 3
16 2 1953 3
17 3 1953 3
18 4 1953 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.