-1

I'd like to create for loop throgh norm1~norm31.

norm1 = norm1 %>% group_by(ID_Pair) %>% summarize(Norm_avg_PCK=mean(ID_avg_PCK,na.rm=T)
, Norm_avg_BT=mean(ID_avg_BT, na.rm=T))

norm2 = norm2 %>% group_by(ID_Pair) %>% summarize(Norm_avg_PCK=mean(ID_avg_PCK,na.rm=T)
, Norm_avg_BT=mean(ID_avg_BT, na.rm=T))

I'd like to create norm1~norm31 as above.

I've tried this code but keep getting the error message.

for (i in 1:31){
nam=paste("norm",i,sep="")
assign(nam,nam %>% group_by(ID_Pair) %>% summarize(Norm_avg_PCK=mean(ID_avg_PCK,na.rm=T)
, Norm_avg_BT=mean(ID_avg_BT, na.rm=T)))}

[Error] Error in UseMethod ("group_by_"): no applicable methid for "group_by_" applied to an object of class "Character"

lalalany
  • 1
  • 1
  • 2
    Hi lalalany, welcome. To make the best use of help here, please provide a minimum reproducible example. That means that you have included enough of your data (for example using `dput`) and code for us to copy and paste it directly into our R sessions, get the error you are getting (which you should include), and produce the output you would like to see (which you should also specify in your question). Thanks and good luck :) – mysteRious Nov 05 '18 at 02:59
  • 1
    `norms <- list(norm1, norm2, ...)`, then `lapply(norms, function(x) x %>% group_by(...) %>% ...)`. Whenever you plan on doing the same thing to multiple similarly- or identically-structured frames, consider putting them in a `list`. https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207 – r2evans Nov 05 '18 at 03:30

2 Answers2

0

There may be better ways to organize your data. But if you like, using get() may solve your problem.

for (i in 1:31){
    nam=get(paste("norm",i,sep=""))
    assign(nam,nam %>% group_by(ID_Pair) %>% summarize(Norm_avg_PCK=mean(ID_avg_PCK,na.rm=T)
, Norm_avg_BT=mean(ID_avg_BT, na.rm=T)))
}
Bing
  • 1,083
  • 1
  • 10
  • 20
0

First, let's put all your norms into a single list:

normlist<-lapply(paste0("norm",1:31),get)

Now, we can use lapply to do your thing for each of the norms:

thing<-function(x) {x %>% group_by(ID_Pair) %>%
  summarize(Norm_avg_PCK=mean(ID_avg_PCK,na.rm=T),
    Norm_avg_BT=mean(ID_avg_BT, na.rm=T))}

lapply(normlist,thing)

Example with some fake data:

a1<-data.frame(id=rep(letters[1:5],3),nums=1:15)
a2<-data.frame(id=rep(letters[6:10],3),nums=16:30)
alist<-lapply(paste0("a",1:2),get)
thing<-function(x) {x %>% group_by(id) %>% summarize(means=mean(nums))}
lapply(alist,thing)
[[1]]
# A tibble: 5 x 2
  id    means
  <fct> <dbl>
1 a        6.
2 b        7.
3 c        8.
4 d        9.
5 e       10.

[[2]]
# A tibble: 5 x 2
  id    means
  <fct> <dbl>
1 f       21.
2 g       22.
3 h       23.
4 i       24.
5 j       25.

If you want to preserve the names, you can use sapply with simplify=FALSE instead of lapply.

iod
  • 7,412
  • 2
  • 17
  • 36