-1

i'm to solve a problem in which the equation goes like this

Values of Band 2 = (Band 3 - Band 1) / (Column name of Band 3 - Column name of Band 1)

i have lots of values in a column so i decided to loop them.

Here is my code:

data4 <- read.csv(file.choose())
XBC <- data4[data4$Crops == "XBC", ]
NB <- data4[data4$Crops == "NB", ]
name <- colnames(NB)[5:125] //store column names into variable name
name <- gsub("[a-zA-Z ]", "", name) // Delete letters from column names so they are numeric
cols <- 5:125 
colsname <- 1:121
NB[cols] <- lapply(NB[cols], as.numeric) // set values of column in NB as numeric
name[colsname] <- lapply(name[colsname], as.numeric) // Set column names to numeric
NB[cols+1] <- ((NB[cols+1] - NB[cols-1]))/((name[colsname+1] - name[colsname-1])) // Equation

This is the error i got. Error in FUN(left, right) : non-numeric argument to binary operator

This is an example of how the columns and rows in NB looks like:

X413.278    X417.897    X422.515
28.86137122 25.83735038 23.18536764
15.21502939 13.81200807 12.47974824
16.0551981  14.54152526 13.02826111
22.16092833 20.66666667 18.69994899
24.35706355 21.73813623 19.65632493
15.74024166 14.17246326 12.71688841
16.64029416 15.14249927 13.55668394
21.13782229 19.40196624 17.63372817

If i sub 1 row of the values into the equation it should be like this:

Values of X417.897 = (23.18536764 - 28.86137122) / (422.515 - 413.278)

and i am going to do this for the rest of the rows and columns

I am using base R

Calvin Chow
  • 31
  • 1
  • 4
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 08 '21 at 05:19
  • i've created an example – Calvin Chow Oct 08 '21 at 05:25
  • It's stil not clear what type of object `NB` is. What does `class(NB)` return? It's better to share a `dput()` which preserves class info rather than whatever the printed representation is. Also, not all variables are defined in the code so we still can't copy/paste the code to run and test is which makes it much more difficult to help. – MrFlick Oct 08 '21 at 05:37
  • NB is a dataframe, – Calvin Chow Oct 08 '21 at 05:41
  • @CalvinChow Did I answer your question below? If so, can you please click the green check mark next to it so that others know this question is closed? Thanks! – NovaEthos Oct 10 '21 at 17:54

1 Answers1

0

name[colsname+1] and name[colsname-1] are still characters, hence why you're getting a "non-numeric argument" error. Try:

NB[cols+1] <- ((NB[cols+1] - NB[cols-1]))/((as.numeric(name[colsname+1]) - as.numeric(name[colsname-1])))

NovaEthos
  • 500
  • 2
  • 10