lolo
lolo

Reputation: 646

R data frames - Suppress Values

Suppose I have the following data frame.

data<-data.frame(index=1:10,col1=c('a','a','a','b','b','b','c','c','c','d'),col2=c(0,4,0,'up',0,0,0,'down',0,0))

 index col1 col2 
   1    a    0
   2    a    4
   3    a    0
   4    b   up
   5    b    0
   6    b    0
   7    c    0
   8    c down
   9    c    0
   10   d    0

How can I get the next sub frame? I have to maintain in the first place unique values ("col1") different from zero or, if no value exists ("col2"), keep the zero.

data.frame(col1=c('a','b','c'),col2=c(4,'up','down'))

col1 col2
 a    4
 b   up
 c down
 d    0

Upvotes: 1

Views: 178

Answers (2)

akrun
akrun

Reputation: 886998

Or we can use data.table. Convert the 'data.frame' to 'data.table' (setDT(data)), grouped by 'col1', if all the values are 0 in 'col2', return the 'col2' or else return values that are not 0

library(data.table)
setDT(data)[, if(all(col2==0)) col2 else col2[col2!=0], col1]
#    col1   V1
#1:    a    4
#2:    b   up
#3:    c down
#4:    d    0

Upvotes: 0

JasonWang
JasonWang

Reputation: 2434

Here is a way using dplyr:

library(dplyr)
# Use stringsAsFactors=FALSE to change the class of col1 and col2
data %>%
  group_by(col1) %>% 
  filter(all(unique(col2) == "0") | (col2 != "0"))
Source: local data frame [4 x 3]
Groups: col1 [4]

  index  col1  col2
  <int> <chr> <chr>
1     2     a     4
2     4     b    up
3     8     c  down
4    10     d     0

Upvotes: 3

Related Questions