Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

r - 无论R中的第三个变量,如何合并日期?(How do I combine dates, regardless of a third variable in R?)

The following is a data example,

(以下是一个数据示例,)

Month        Year     Tornado    Location
January      1998     3         Illinois
February     1998     2         Illinois
March        1998     5         Illinois
January      1998     1         Florida
January      2010     3         Illinois

Here is what I want it to look like essentially,

(这就是我想要的样子,)

Date      Tornado
1998-01   4
1998-02   2
1998-03   5
2010-01   3

So, I want to combine the Year and Month into one, new column.

(因此,我想将“年”和“月”合并为一个新的列。)

The locations do not matter, I want to know the total number of tornadoes for January, 1998, and etc. I have the following code, but do not know how to change it to incorporate both the variables I want, or if this is even the correct code for what I am attempting to do.

(位置无关紧要,我想知道1998年1月的龙卷风总数,等等。我有以下代码,但是不知道如何更改它以合并我想要的两个变量,或者甚至是我尝试执行的正确代码。)

mydata$Date <- format(as.Date(mydata$month), "%m-%Y")

The real dataset is far too large to fix manually.

(实际数据集太大,无法手动修复。)

I am basically attempting to make this data into time series data.

(我基本上是试图将这些数据转换为时间序列数据。)

  ask by Cynical F translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to apply some data transformation before applying How to sum a variable by group

(您需要先进行一些数据转换,然后再应用如何按组对变量求和)

aggregate(Tornado~Date, transform(df, Date = format(as.Date(paste(Month,Year,"01"),
                        "%B %Y %d"), "%Y-%m")), sum)

#     Date Tornado
#1 1998-01       4
#2 1998-02       2
#3 1998-03       5
#4 2010-01       3

data

(数据)

df <- structure(list(Month = structure(c(2L, 1L, 3L, 2L, 2L), 
.Label = c("February", "January", "March"), class = "factor"), 
Year = c(1998L, 1998L,1998L, 1998L, 2010L), 
Tornado = c(3L, 2L, 5L, 1L, 3L), Location = structure(c(2L, 
2L, 2L, 1L, 2L), .Label = c("Florida", "Illinois"), class = "factor")), 
class = "data.frame", row.names = c(NA, -5L))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...