Home > Mobile >  Error in FUN(left, right) : non-numeric argument to binary operator
Error in FUN(left, right) : non-numeric argument to binary operator

Time:10-07

i'm trying to add values to each individual columns in a specific rows which i'm using a loop but it keeps giving the error of "non-numeric argument to binary operator" so maybe i am thinking the program reads the index value of the column?

This is my code:

col1st <- colnames(NB1stRow)[5:74]
for(i in seq_along(col1st)){
  NB1stRow[i] <- NB1stRow[i]*2
}

Here's how a column would look like

NB1stRow[6]
   X417.897
1  21.29759
2  22.52447
3  25.59260
4  29.67289
5  34.45366
6  30.30945
7  28.02665
8  28.13356
9  31.67405
10 28.65952
11 28.49534
12 32.18732
13 35.24368
14 32.02267
15 30.92876

I am using base R.

CodePudding user response:

For example,

dummy <- matrix(c(1:25), nrow = 5, byrow = TRUE) %>% as.data.frame()
  V1 V2 V3 V4 V5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13 14 15
4 16 17 18 19 20
5 21 22 23 24 25

with this data, it will work.

for (i in seq_along(colnames(dummy))){
  dummy[i] <- dummy[i]*2
}
  V1 V2 V3 V4 V5
1  2  4  6  8 10
2 12 14 16 18 20
3 22 24 26 28 30
4 32 34 36 38 40
5 42 44 46 48 50

when change one values into text, like

dummy <- matrix(c(1:25), nrow = 5, byrow = TRUE) %>% as.data.frame()
dummy[3,4] <- "a"
  V1 V2 V3 V4 V5
1  1  2  3  4  5
2  6  7  8  9 10
3 11 12 13  a 15
4 16 17 18 19 20
5 21 22 23 24 25

for (i in seq_along(colnames(dummy))){
  dummy[i] <- dummy[i]*2
}

Error in FUN(left, right) : non-numeric argument to binary operator

try check str(NB1stRow[,c(5:74)]) have any chr or factor or etc

CodePudding user response:

First check if the class of the data is numeric. str(NB1stRow) will show you classes of each column. If they are not numeric, turn them to numeric by -

cols <- 5:74
NB1stRow[cols] <- lapply(NB1stRow[cols], as.numeric)

Multiplication (*) doesn't require loop and it can be applied to dataframe directly so you can do

NB1stRow[cols] <- NB1stRow[cols] * 2

CodePudding user response:

Assuming that columns 5:74 are numeric, the problem is that seq_along(col1st) is 1:70 so it is trying to double those columns, not columns 5:74. Using DF to represent the data frame we want:

ix <- 5:74
for(i in ix) DF[i] <- 2 * DF[i]

or just

DF[ix] <- 2 * DF[ix]
  •  Tags:  
  • r
  • Related