user1021713
user1021713

Reputation: 2203

Extract columns in data frame with specific values

I want to change the value of the alternate columns of the data frame to 0 which are less than 1. E.g.

abc 1   ghf 3
def 3   ftr 6
scf 0.2 ugh 1

All the values of second and the third column that are less than one should become zero.

Is there a way to do it in R?

Upvotes: 0

Views: 1877

Answers (2)

IRTFM
IRTFM

Reputation: 263301

This actually works, and it may be difficult to improve on its simplicity:

df[ df<1 ] <- 0

Alternate approach (but less compact): When which is used with arr.ind=TRUE returns a two-column matrix of the rows and columns where the condition is TRUE. You can use this with [<-.data.frame, but it needs to be done as numeric indices

 idxs <- which(df <1, arr.ind=TRUE)
#Warning messages:
#1: In Ops.factor(left, right) : < not meaningful for factors
#2: In Ops.factor(left, right) : < not meaningful for factors
### Perfectly safe to ignore the warning
 df[ idxs[,1], idxs[,2] ] <- 0
 df
#------------------
   V1 V2  V3 V4
1 abc  1 ghf  3
2 def  3 ftr  6
3 scf  0 ugh  1

Upvotes: 5

vaettchen
vaettchen

Reputation: 7659

It would help if you gave your data in a format that can be used immediately dput( myData ), the output of which can assigned to a variable:

> df <- structure(list(V1 = structure(1:3, .Label = c("abc", "def", "scf"                                        
), class = "factor"), V2 = c(1, 3, 0.2), V3 = structure(c(2L, 1L,                                          
3L), .Label = c("ftr", "ghf", "ugh"), class = "factor"), V4 = c(3L,                                      
6L, 1L)), .Names = c("V1", "V2", "V3", "V4"), row.names = c(NA,                                          
-3L), class = "data.frame")

> df
   V1   V2  V3 V4 
1 abc    1 ghf  3
2 def    3 ftr  6 
3 scf  0.2 ugh  1

You say "all the values of second and the third column..." but you probably mean "second and fourth...". Here is what I would do:

> df$V2 <- ifelse( df$V2 < 1, 0, df$V2 )
> df$V4 <- ifelse( df$V4 < 1, 0, df$V4 )
> df
   V1 V2  V3 V4
1 abc  1 ghf  3
2 def  3 ftr  6
3 scf  0 ugh  1

More see ?ifelse, but I think this should help already.

Upvotes: 1

Related Questions