使用R和Lubridate从数据框中删除不满足多个条件的所有行

时间:2017-04-17 14:38:20

标签: r dataframe lubridate

我正在尝试使用名为test的日期数据框:

structure(list(`1` = structure(c(1301641140, 1306861140, 1306947540, 
1310403540, 1312394340, 1314982740, 1320044340, 1321599540, 1323413940, 
1325660340, 1329116340, 1331017140, 1335808740, 1338220740, 1341075540, 
1341161940, 1343926740, 1346518740, 1351537140, 1354172340, 1356249540, 
1358837940, 1359961140, 1362376740, 1364972340, 1369846740, 1371056340, 
1374080340, 1377968340, 1378832340, 1382774340, 1385625540, 1386917940, 
1389077940, 1393484340, 1393873140, 1397631540, 1401292740, 1403024340, 
1404320340, 1408726740, 1409677140, 1412269140, 1416376740, 1418367540, 
1420700340, 1424415540, 1425625140, 1428220740, 1431359940, 1434560340, 
1438189140, 1438707540, 1441213140, 1444237140, 1448261940, 1450598340, 
1453186740, 1455087540, 1456984740, 1461776340, 1464713940, 1465919940, 
1469465940, 1471366740, 1473440340, 1476896340, 1479711540, 1481353140, 
1483862340, 1486709940, 1489647540), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), `2` = structure(c(1302533940, 1306850340, 
1308153540, 1311782340, 1312383540, 1314892740, 1318867140, 1322643540, 
1322726340, 1325667540, 1329724740, 1332950340, 1335794340, 1338307140, 
1340639940, 1343228340, 1343833140, 1346767140, 1349366340, 1354175940, 
1355385540, 1358845140, 1362049140, 1363251540, 1366293540, 1369843140, 
1371052740, 1374073140, 1375977540, 1378828740, 1380725940, 1384415940, 
1386925140, 1390985940, 1391680740, 1393847940, 1398686340, 1400770740, 
1403103540, 1405349940, 1407340740, 1410364740, 1412175540, 1416301140, 
1418288340, 1420707540, 1424336340, 1425628740, 1428591540, 1432141140, 
1435157940, 1436975940, 1438790340, 1441292340, 1444226340, 1448269140, 
1449215940, 1453201140, 1455091140, 1458550740, 1461859140, 1464278340, 
1466697540, 1469545140, 1472133540, 1473951540, 1475596740, 1478015940, 
1482137940, 1483945140, 1486713540, 1490803140), class = c("POSIXct", 
"POSIXt"), tzone = "UTC")), .Names = c("1", "2"), row.names = c(NA, 
-72L), class = c("tbl_df", "tbl", "data.frame"))

并从月份编号不是1,2,3,11或12(1月2月,3月,11月,12月)的每一列中删除ROWS。我可以像使用lubridate那样得到月份数:

apply(test, 2, month)

如何从上述应用中返回不需要的数字的每一列中删除行?

修改
上面的输出实际上是一个测试数据帧。我的实际数据框有71列。

2 个答案:

答案 0 :(得分:3)

另一种可能性,

    <PublishingWebControls:EditModePanel runat="server">

如果您有1列满足条件而另一列不满足的行,那么您可以用NA替换不需要的日期,即

library(lubridate)

test[rowSums(sapply(test, function(i) month(i) %in% c(1,2,3,11,12))) == ncol(test),]

答案 1 :(得分:0)

您没有提及要测试的列,因为列12都有日期时间。

这是针对列1

library(data.table)
dt <- data.table(df)
dt[month(`1`) %in% c(1, 2, 3, 11, 12)]