Eric K
Eric K

Reputation: 15

saving multiple row outputs from a for loop to an object in R

How do you save rows of outputs from a for loop to a R object? Below I am trying to iterate by group, and save the outputs to a new data frame in R.

I can get the output to print in the console, but am unable to save it to an object. What is the best way to do this?

#dataset

mat = matrix(1:30, nrow = 10, ncol = 3)    #dataset values

group = c(1,1,1,2,2,2,3,3,3,3)             #three groups

df = as.data.frame(cbind(mat, group))      #dataset to use
df[,1] = as.numeric(df[,1])
df[,2] = as.numeric(df[,2])
df[,3] = as.numeric(df[,3])
df[,4] = as.factor(df[,4])


#function
  
  funk = function(x) {
    V1 = mean(x[,1])
    V2 = min(x[,2])
    V3 = max(x[,3]) 
    c(V1,V2,V3)
  }

For loop

#for loop

iterate  <- function(x) {
  z = levels(x[,4])
  z = as.numeric(z)
  
  for (i in z) {
    y <- subset(x, x[,4] == i)
    out <- funk(y)
    out = as.data.frame(t(out))
    print(out)
                     #!! how to save to an object with three rows (one for each group)
    
  }
}

iterate(df)

Output

Upvotes: 1

Views: 296

Answers (2)

MonJeanJean
MonJeanJean

Reputation: 2906

You can use the function assign() inside the loop to save the object:

Adding assign(paste0("out",i,sep = "_"), out) will create for each iteration an object called out_i with i the number of iteration.

Upvotes: 0

r2evans
r2evans

Reputation: 160447

You might use dplyr for this,

df %>%
  group_by(group) %>%
  summarize(V1 = mean(V1), V2 = min(V2), V3 = max(V3))
# # A tibble: 3 x 4
#   group    V1    V2    V3
#   <fct> <dbl> <dbl> <dbl>
# 1 1       2      11    23
# 2 2       5      14    26
# 3 3       8.5    17    30

Or you can do it with base R, not necessarily as elegantly:

do.call(
  rbind,
  by(df, df$group, FUN = function(z) data.frame(group = z$group[1], V1=mean(z$V1), V2=min(z$V2), V3=max(z$V3)))
)
#   group  V1 V2 V3
# 1     1 2.0 11 23
# 2     2 5.0 14 26
# 3     3 8.5 17 30

Upvotes: 1

Related Questions