0

I have this table here in R.

It's called d and the results are:

                  V1       V2       V3       V4         V5   V6           V7        V8
1    testtest_no_2nd  14.06863 11.50424 333173.1        0.0  0.00000      NaN       0.00
2    testtest1_no_2nd 14.50265 11.89501 387709.7    54536.6  0.43402 125654.6        NaN
3    testtest2        14.55234 11.95746 402124.0    14414.3  0.04969 290084.5  164429.95
4    testtest3        14.78606 12.14149 453059.3    50935.3  0.23372 217933.0  -72151.53
5    testtest4        15.16970 12.51004 496142.1    43082.8  0.38364 112300.1 -105632.92

What i need is that first i need to convert the Nan Values into 0 and then i need to delete the first element of the V8 Vector and add a 0 value at the end. I would be now

V8
0.00
164429.95
-72151.53
-105632.92

After that i need to remove all rows of the d table that have a V8<0

Someone help me with that? Thanks.

Karsten W.
  • 17,826
  • 11
  • 69
  • 103
Dea12
  • 55
  • 1
  • 2
  • 7
  • possible duplicate of [remove row with nan value](http://stackoverflow.com/questions/5961839/remove-row-with-nan-value) – llrs Mar 25 '14 at 09:51
  • Did you thought about subset? And then do the changes you want? – llrs Mar 25 '14 at 09:52
  • I din't duplicate the question, first of all, and frankly i'm new to this, and didn't know what to use... – Dea12 Mar 25 '14 at 09:54
  • The OP is not asking to remove all cases that contain NaN's, but rather to convert them to zeroes. – jbaums Mar 25 '14 at 09:57
  • And i just need the dataframe to remain as it is, without removing anything yet, i just want to change the V8 column so i can do further things with it.. – Dea12 Mar 25 '14 at 09:59

1 Answers1

0

This is easier with matrices, but to do it with your data.frame, try the following:

d.new <- do.call(cbind.data.frame, lapply(d, function(x) {
  x[is.nan(x)] <- 0
  x
}))

d.new['V8'] <- c(d.new[-1, 'V8'], 0)

subset(d.new, V8 >= 0)

                V1       V2       V3       V4      V5      V6       V7     V8
1  testtest_no_2nd 14.06863 11.50424 333173.1     0.0 0.00000      0.0      0
2 testtest1_no_2nd 14.50265 11.89501 387709.7 54536.6 0.43402 125654.6 164430
5        testtest4 15.16970 12.51004 496142.1 43082.8 0.38364 112300.1      0

Now, if d were a matrix with col 1 as row.names, it would be a little simpler:

m <- as.matrix(d[, -1])
row.names(m) <- d[, 1]
m[is.na(m)] <- 0
m[m[, 'V8'] >= 0, ]
jbaums
  • 27,115
  • 5
  • 79
  • 119