Home > OS >  Loop with table names in R
Loop with table names in R

Time:10-18

I have three tables:

AAA_PROSTATEx, BBB_PROSTATEx, CCC_PROSTATEx,

and I want to process and create the tables as followed, but I don't know how to use loops to solve them. Ideally, there will be two loops:

### loop #1 ####
AAA_PROSTATEx_1 <- AAA_PROSTATEx[48:57, ]
BBB_PROSTATEx_1 <- BBB_PROSTATEx[48:57, ]
CCC_PROSTATEx_1 <- CCC_PROSTATEx[48:57, ]

# **name**_PROSTATEx_1 <- *name**_PROSTATEx[48:57, ]



### loop #2 ###
AAA_PROSTATEx_1  <-                                                   
  AAA_PROSTATEx_1 %>%
  mutate(V2.T2.Total = select(., V2.T2.Artef:V2.T2.Sag) %>%
           rowSums()
  )

BBB_PROSTATEx_1  <-                                                   
  BBB_PROSTATEx_1 %>%
  mutate(V2.T2.Total = select(., V2.T2.Artef:V2.T2.Sag) %>%
           rowSums()
  )


CCC_PROSTATEx_1  <-                                                   
  CCC_PROSTATEx_1 %>%
  mutate(V2.T2.Total = select(., V2.T2.Artef:V2.T2.Sag) %>%
           rowSums()
  )



# **name**_PROSTATEx_1  <-                                                  
  **name**_PROSTATEx_1 %>%
  mutate(V2.T2.Total = select(., V2.T2.Artef:V2.T2.Sag) %>%
           rowSums()
  )

CodePudding user response:

You can use assign and get to refer a variable by character name


tables = c("AAA_PROSTATEx_1", "BBB_PROSTATEx_1", "CCC_PROSTATEx_1")

### loop #1 ####
for(table in tables){
    assign(table, get(table)[48:57, ])
}

# **name**_PROSTATEx_1 <- *name**_PROSTATEx[48:57, ]

### loop #2 ###
for(table in tables){
    assign(table, get(table) %>%
      mutate(V2.T2.Total = select(., V2.T2.Artef:V2.T2.Sag) %>%
               rowSums()
      ))
}

However, as @tacoman suggests, it would be better to work with a list of dataframes instead

CodePudding user response:

If you want to keep it simple:

library(dplyr)
tables <- list(AAA_PROSTATEx, BBB_PROSTATEx, CCC_PROSTATEx)

lapply(tables, function(x) {
  x %>%
    dplyr::filter(dplyr::row_number() %in% 48:57) %>%
    dplyr::mutate(V2.T2.Total = dplyr::select(.,V2.T2.Artef:V2.T2.Sag) %>%
           rowSums())
})
  • Related