简体   繁体   中英

Loop in R: Store output in a dataframe

Here is the problem I am currently facing: I have a data frame (let's call A) of 96 observations (rows) and 16 variables (columns). I also have a rotation of 9 column vectors (from a Principal Components Analysis) of 16 elements (coefficients for each of the 16 variables of A).

The PCA rotations are saved as such:

ph=prcomp(home[ ,3:17], scale. = TRUE)
Home_vec=-round(ph$rotation[ ,1:9], 3)

Now, singularly I have been able to multiply one of the rows of my data frame by the object Home_vec and the output is equal to multiplying the row by each of the 9 PC columns, and applying cbind.

For example, the row input:

TEAM=c(5, 1503, 26.31, 16.2, 0.099, 33, 28, 368, 35, 15, 84, 942, 528, 33, 315)

My new output:

TEAM.1=round(TEAM*Home_vec,3)

I have created a for-loop which carries out this procedure for each of the 96 observations in my data frame.

F=function(x){
  x*Home_vec
} 

for(i in 1:96){
    print(F(home[i,2:17]))
}

The only problem is - I'm struggling to save the output (which is a 96 by 9 data frame) as a new object.

Any help would be appreciated, Thanks!

Try doing the following with your loop:

I am using the package dplyr.

x <- "" %>% data.frame

for(i in 1:96){
y <- F(home[i,2:17]))
x <- bind_rows(x,y)
}

x <- x %>% .[-1,-1]

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