简体   繁体   中英

Referencing variable column names within a subset within a for loop in R

I'm trying to build a for-loop that references a different column name with each iteration. The data table I'm subsetting is called "Combined" and the columns I'm trying to reference are simply named 1, 2, 3, all the way to 84. I'm hoping each output object created by the for loop will calculate the max value in column i (in "Combined") for each unique value in column "sci_name" (also in "Combined").

This is what I've come up with so far:

X <- c(1:84)

for (i in X) {
name <- paste("er", i, sep="_")
assign(name, Combined[,max(`i`), by=sci_name])
}

This code runs but it simply assigns the same values to every position within each of the er_# output objects, rather than actually taking the max for column i.

Outside of a for loop, I've found that this code works on it's own, but can't figure out how to get the column title number to be changeable within the loop (and would prefer not to do all 84 iterations by hand):

er_1 <- Combined[,max(`1`), by=sci_name]

You didn't provide any useable data so I'll use the mpg dataset:

library(tidyverse)

mpg %>% 
    group_by(cyl) %>% 
    summarize(across(c(cty, hwy), max))

This will organize the output in a tibble.

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