简体   繁体   中英

Using For Loop in R to loop through a dataframe

I have a function called Produce_Output . It takes an X variable and a Y variable then in R carries out some calculations, SQL data retrievals, saves a plot to a file location etc. the function itself doesn't produce anything but triggers other actions.

I want to run this function through a data frame which has been setup for it. The dataframe has 8464 obs and 2 variables. I would like to use the function and pass each 2 variables to the function an observation at a time.

calling the function as follows

for (Data_To_Process) {
    Produce_Output(TableA$Column1, TableA$Column2)
}

I get the following error

Error in $<-.data.frame ( *tmp* , "OND", value = c(3379L, 3121L, 1699L, : replacement has 8464 rows, data has 3

I read a post on here about the data having NULLs, I've checked that and it doesn't. I also don't understand what it replacing what with. I just want it to process the first row, then the next... then the next... as I said the function has no output but triggers other procedures using the two values inserted. Any help would be appreciated.

Rui Barradas - You are perfectly correct that was the issue. I was aware of the index method for the loop but had only access to instances where one column was being used so didn't understand how to reference other columns in the syntax. Thanks for your help

"You are passing the entire columns, not rows. It could be something like for(i in 1:nrow(TableA)){Produce_Output(TableA$Column1[i], TableA$Column2[i])}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM