Change Variable Name in For Loop Using R

Loop in R using changing variable to write and name files

You can't use paste to create a variable name as you've listed. You can enclose it within assign or eval, however it may be easier to instead store your results within a data frame. Below is an example of what I believe you're trying to achieve. I have also replaced your while loop and counter with a for loop iterating over years:

YearsDays <- read.csv("Data\\Years.csv") # a df with 49 obs. of 3 variables (year, start day, and end day

output <- data.frame(year = YearsDays[,1], rain_r = NA)

for (idx in seq(nrow(YearsDays))){

#set variables to loop through
year <- YearsDays[idx,1]
startday <- YearsDays[idx,2]
endday <- YearsDays[idx,3]

BC_rain.slice <- Biased_corrected.array[,,startday:endday]
annual_rain <- apply(BC_rain.slice, c(1,2), sum)

#save data in a raster
output$rain_r[output$year == year] <- raster(t(annual_rain, xmn=min(x), xmx=max(x), ymn=min(y), ymx=max(y), crs=WGS84))

}

Loop to change one part of a variable name and repeat the command

You can use lapply :

cols <- paste0('nd', 1:40)
dataset[paste0(cols, '_4_digits')] <- lapply(dataset[cols], substr, 2, 5)

Or in dplyr :

library(dplyr)
dataset %>%
mutate(across(starts_with('nd'), list(digits = ~substr(., 2, 5))))

Changing a variable name within the formula in a loop in R

Get all the variables in a vector and create a formula object using sprintf/paste0.

library(survey)

cols <- c('var1', 'var2')
#If you want all the variables that have 'var' in it.
#cols <- grep('var', names(df), value = TRUE)
result <- lapply(cols, function(x) {
svychisq(as.formula(sprintf('~%s + strata', x)), svy_design)
})

Dynamic variable names to mutate variables in for-loop

As we are passing string, convert to symbol and evaluate (!!)

func <- function(i) {

mutate(df1, !!i := case_when(!is.na(!! rlang::ensym(i)) ~ as.character(!! rlang::ensym(i)),
is.na(!!rlang::ensym(i)) & var0 != '1' ~ '4444',
TRUE ~ '0'))
}

-testing

for(i in vars) {
df1 <- func(i)
}
df1
var0 var1 var2 var3
1 1 0 1 NA
2 2 1 4444 1
3 2 0 0 0
4 1 1 0 4444
5 1 0 1 1
6 2 4444 4444 NA
7 2 4444 4444 1

We may do this with across as well

df1 %>%
mutate(across(all_of(vars),
~ case_when(!is.na(.) ~ as.character(.),
is.na(.) & var0 != '1' ~ '4444', TRUE ~ '0')))
var0 var1 var2 var3
1 1 0 1 NA
2 2 1 4444 1
3 2 0 0 0
4 1 1 0 4444
5 1 0 1 1
6 2 4444 4444 NA
7 2 4444 4444 1

Replace variable name in loop in R

Yes, but the best approach is to use lists and the lapply or sapply functions instead of loops.

hour.in <- mget( paste0('hour_', 1:10) )
hour.out <- lapply( hour.in, function(x) aggregate(x$freq,
by=list(country=x$country), FUN=sum) )
names(hour.out) <- paste0('hour_', 1:10)

Now all the results are in hour.out and can be accessed individually, or further processed using lapply or sapply.



Related Topics



Leave a reply



Submit