此问题与我之前的问题Subsetting a dataframe for a specified month and year
有关我使用命令
sales< - read.csv(“mysales.csv”,colClasses =“character”)
获取如下所示的数据框:
row date pieces income
1 21/11/2011 49 220.5
2 22/11/2011 58 261
3 23/11/2011 23 103.5
4 24/11/2011 57 256.5
我想使用上一个问题中提供的代码为2011年11月创建一个子集,但各种尝试都失败了。因此,我在控制台中写了一个检查:
format.Date(sales[1,1], "%Y")=="2011"
答案是:
[1] FALSE
此外:
format(as.Date(sales[1,1]), "%d/%m/%Y")
[1] "20/11/21"
我怎么能,至少知道日期格式发生了什么?
我应该如何使用以下代码对数据框进行子集化?
subset(sales, format.Date(date, "%m")=="11" & format.Date(date, "%Y")=="2011")
很抱歉,如果我的问题不明确,但我面临的问题也不清楚。
(编辑以更正格式)
答案 0 :(得分:1)
目前,你认为日期真的只是字符串。您需要使用Date
将它们转换为as.Date
个对象,并为此指定它们所在的格式(%d/%m/%Y
)或R不会为您猜测它。
sales <- data.frame(date = c("21/11/2011", "21/11/2011", "23/11/2012", "24/11/2012"),
pieces = c(49,58,23,57,34),
income = c(220.5, 261, 103.5, 256.5, 112))
class(sales$date)
# [1] "factor"
sales$date <- as.Date(sales$date, "%d/%m/%Y")
class(sales$date)
# [1] "Date"
subset(sales, format.Date(date, "%m")=="11" & format.Date(date, "%Y")=="2011")
# date pieces income
# 1 2011-11-21 49 220.5
# 2 2011-11-21 58 261.0
答案 1 :(得分:0)
为了使答案更加通用,我又增加了一个月。
工作数据如下:
date pieces income
1 21/11/2011 49 220.5
2 22/11/2011 58 261.0
3 23/11/2011 23 103.5
4 24/11/2011 57 256.5
5 23/12/2011 50 240.0
有很多方法可以做到这一点。我经常使用的是strsplit和lapply。
sale$date1<-as.Date(sale$date, "%d/%m/%Y") # let R know the date format
# Create a column of months by splitting the dates into 3 parts and grabbing the middle
# part which is months
sale$months<-lapply(strsplit(as.character(sale$date1), "-"), function(x){x[2]})
# finally keep only the data for the month of November
required<-subset(sale[which(sale$months==11),], select=-c(months,date1))
date pieces income
1 21/11/2011 49 220.5
2 22/11/2011 58 261.0
3 23/11/2011 23 103.5
4 24/11/2011 57 256.5