R with replacement in dataframe, error "non-existent rows not allowed"

Viewed 1941

I have an odd problem when doing replacement in my dataframe. I want to keep the topN values in every column, and replace others with zero, here is my function:

remain_topN_word <- function(df, n) {
  for(col in colnames(df)) {
    topV <- sort(df[,col],decreasing = T)[n]
    if(topV > 0) {
      df[df[, grep(col, colnames(df))] < topV, col] <- 0
    }
    print(col)
  }
  return(df)
}

my data is something like this:

c <- data.frame(replicate(10,rnorm(9000)))

then i use my function, and get the error

 d <- remain_topN_word(c[,1:10], 3)
Error in `[<-.data.frame`(`*tmp*`, df[, grep(col, colnames(df))] < topV,  : 
  non-existent rows not allowed
Called from: `[<-.data.frame`(`*tmp*`, df[, grep(col, colnames(df))] < topV, 
    col, value = 0)

if i only use the function with my first 9 columns or my last 2 columns, everything will be ok.

d <- remain_topN_word(c[,1:9], 3)
[1] "X1"
[1] "X2"
[1] "X3"
[1] "X4"
[1] "X5"
[1] "X6"
[1] "X7"
[1] "X8"
[1] "X9"

d <- remain_topN_word(c[,9:10], 3)
[1] "X9"
[1] "X10"

here is my sessionInfo: R version 3.4.0 (2017-04-21) Platform: x86_64-apple-darwin15.6.0 (64-bit) Running under: OS X El Capitan 10.11.3

i would appreciate it if u can figure this out, thank you in advance.

0 Answers
Related