我想从数据框中删除所有零。
PRICES SALES PURCHASES MARGINAL RESIDUAL AMPDCH MW.PUMPED_B
1: 81 1391.830 2061.830 Ccgt 1918 81 140.00000
2: 81 1315.405 1985.405 Ccgt 1858 81 140.00000
3: 81 1192.031 1862.031 Ccgt 1746 0 0.00000
4: 81 1138.187 1747.216 Ccgt 1622 0 0.00000
5: 81 1138.868 1666.639 Ccgt 1534 81 49.41176
6: 81 1140.571 1628.348 Ccgt 1503 0 0.00000
我试着用
df[ !rowSums(df[,colnames(df)[(3:ncol(df))]]==0)==ncol(df)-2, ]
但是零仍然在数据框中。有没有人知道任何合适的解决方案。
预期输出看起来像那样
PRICES SALES PURCHASES MARGINAL RESIDUAL AMPDCH MW.PUMPED_B
1 81 1391.830 2061.830 Ccgt 1918 81 140.00000
2 81 1315.405 1985.405 Ccgt 1858 81 140.00000
3 81 1138.868 1666.639 Ccgt 1534 81 49.41176
答案 0 :(得分:2)
尝试
df1[!!rowSums(df1[, 6:7, with=FALSE])]
# PRICES SALES PURCHASES MARGINAL RESIDUAL AMPDCH MW.PUMPED_B
#1: 81 1391.830 2061.830 Ccgt 1918 81 140.00000
#2: 81 1315.405 1985.405 Ccgt 1858 81 140.00000
#3: 81 1138.868 1666.639 Ccgt 1534 81 49.41176
答案 1 :(得分:1)
这是一个简单明了的解决方案:
> df[-row(df)[df == 0],]
PRICES SALES PURCHASES MARGINAL RESIDUAL AMPDCH MW.PUMPED_B
1: 81 1391.830 2061.830 Ccgt 1918 81 140.00000
2: 81 1315.405 1985.405 Ccgt 1858 81 140.00000
5: 81 1138.868 1666.639 Ccgt 1534 81 49.41176
答案 2 :(得分:0)
# the same basic idea using "any"
df[!apply(df[,6:7] == 0, 1, FUN = any, na.rm = TRUE),]
# PRICES SALES PURCHASES MARGINAL RESIDUAL AMPDCH MW.PUMPED_B
#1: 81 1391.830 2061.830 Ccgt 1918 81 140.00000
#2: 81 1315.405 1985.405 Ccgt 1858 81 140.00000
#5: 81 1138.868 1666.639 Ccgt 1534 81 49.41176