0

For my university internship I have lots of datasets that I should do the same functions, in Excel, over and over for each one. I decided to do an R script and I'm almost finishing, I just need help in this last step.

I have some countys productions by year, and I want to multiply all year columns in this list by a specific column, the latitude column, and the result should come in the form of new columns named xlat+year.

I tried lots of for loops but I can't get it right.

This is an example in Excel of what I want to do in R

This is an example in Excel of what I want to do in R. I multiplied the F2 column (production) by the D2 column (latitude).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tnorio
  • 61
  • 1
  • 7
  • 1
    It's easier to help you if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input. Show the code you tried and describe exactly what you mean by "can't get it right." – MrFlick Jan 11 '18 at 16:02
  • 1
    This would be easier if you reshaped your data to *long format*. All "year" columns should really be just one column with a second column giving the year. You might benefit from reading [Hadley's paper](http://vita.had.co.nz/papers/tidy-data.html) regarding tidy data. – Roland Jan 11 '18 at 16:04

1 Answers1

0

Here is how you can do it using a simple sapply instead of a for loop

. Note: I will be creating sample data for better understanding.

test_df <- data.frame(LAT = -1*sample(50), xlat91 = sample(50), xlat92 = sample(50), xlat93 = sample(50), xlat94 = sample(50)) # sample data
test_df2 <- sapply(2:5, function(x) test_df["LAT"]*test_df[,x]) # alternative to for loop you were looking for
test_df3 <- cbind(test_df,test_df2)
new_cols <- c("xlat+91","xlat+92","xlat+93","xlat+94")
names(test_df3)[6:9] <- new_cols
test_df3 #your final answer
Gompu
  • 415
  • 1
  • 6
  • 21