1

I have facing an error recently, i have a data frame called Centroid like this( this is a small piece of the real archive)

      X1989  X1990  X1991       LAT            LON
   1     10    11    10   -44,3517712669 -22,9847296224
   2  12040 12040 14589   -42,2932250108 -22,7536045078
   3      3     3     3   -43,9128279672 -22,4248877183
   4     20    20    20   -44,2046056169 -22,4533649489

And i need to multiply each year column by the LAT column and LON column as well.

I tried doing that with a for loop

LAT<- Centroid[,29]
xlat<-as.list
for ( col in Centroid[,1:28]) {
  xlat<- col * Centroid[,29]
  cbind(TABTRUE,xlat, make.col.names= TRUE)

}

but I get this error:

Error in col * Centroid[, 29] : non-numeric argument to binary operator.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
tnorio
  • 61
  • 1
  • 7
  • 2
    I'm guessing by the commas in the LAT and LON values that those columns are of type character, not numeric. What does `class(Centroid$LAT)` say? – neilfws Apr 13 '18 at 02:52
  • Possible duplicate of https://stackoverflow.com/q/29665428/3358272 – r2evans Apr 13 '18 at 03:29
  • when i tipe class(Centroid$LAT) it returns: character. i havent tought about that comma thing.... – tnorio Apr 13 '18 at 14:56
  • i also changed all the commas `.` with a `.`, before adding it to the dataframe, but the result of `class(Centroid$LAT)` is still `character` :/ – tnorio Apr 13 '18 at 16:16

1 Answers1

0

This is a good candidate where dplyr::mutate_at can help. There is no need for a for-loop either.

Clearly data in LAT and LON columns contains comma , and those are non-numeric columns.

Now, first use mutate_at to convert LAT and LON columns to numeric (after replacing , with . ) and then use mutate_at again to multiply columns with year by LAT.

library(dplyr)

Centroid %>% mutate_at(vars(c("LAT","LON")),funs(as.numeric(gsub(",","\\.",.)))) %>%
  mutate_at(vars(starts_with("X")),funs(.*LAT))

#          X1989        X1990        X1991       LAT       LON
# 1    -443.5177    -487.8695    -443.5177 -44.35177 -22.98473
# 2 -509210.4291 -509210.4291 -617015.8597 -42.29323 -22.75360
# 3    -131.7385    -131.7385    -131.7385 -43.91283 -22.42489
# 4    -884.0921    -884.0921    -884.0921 -44.20461 -22.45336

Data:

Centroid <- read.table(text =
"X1989  X1990  X1991       LAT            LON
1     10    11    10   -44,3517712669 -22,9847296224
2  12040 12040 14589   -42,2932250108 -22,7536045078
3      3     3     3   -43,9128279672 -22,4248877183
4     20    20    20   -44,2046056169 -22,4533649489",
header = TRUE, stringsAsFactors = FALSE)
MKR
  • 19,739
  • 4
  • 23
  • 33
  • 1
    it does work! thats great. im kinda new to R and im not intimate with the dplyr. but i will learn! thanks bro – tnorio Apr 13 '18 at 16:18