删除R矩阵中的零列

时间:2020-10-07 11:02:10

标签: r

我有一个像这样的矩阵

structure(list(Item = structure(c(3L, 1L, 4L, 2L), .Label = c("boat", 
"bus ", "Car", "jeep"), class = "factor"), Cost = structure(c(3L, 
1L, 2L, 4L), .Label = c("E.02", "E0.23", "E2.03", "E5.60"), class = "factor"), 
BMW = c(0, 2.5, 12, 0.089), VW = c(0.56, 4.56, 0, 0.054), 
Bens = c(0.06, 5.01, 4.57, 0), Pet = c(0.02, 5.31, 0.36, 
45)), class = "data.frame", row.names = c(NA, -4L))

我需要删除具有零的列。 我尝试过申请

   row_sub = apply(data, 1, function(row) all(row !=0 ))
   data[row_sub,]

但是它不起作用

预期产量

Item Cost BMW VW   Bens Pet
boat E.02 2.5 4.56 5.01 5.31 

1 个答案:

答案 0 :(得分:1)

df[df==0]<-NA
df<-na.omit(df)
df

Item Cost BMW   VW Bens  Pet
boat E.02 2.5 4.56 5.01 5.31