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 sym
bol 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
Dplyr::Select Function Clashes With Mass::Select
How to Extract Plot Axes' Ranges For a Ggplot2 Object
Converting Multiple Columns from Character to Numeric Format in R
Difference Between the == and %In% Operators in R
How to Efficiently Calculate Distance Between Pair of Coordinates Using Data.Table :=
Reshaping Time Series Data from Wide to Tall Format (For Plotting)
Plotting Grouped Bar Charts in R
How to Listen For More Than One Event Expression Within a Shiny Eventreactive Handler
Increase Distance Between Text and Title on the Y-Axis
Merging Two Data Frames Using Fuzzy/Approximate String Matching in R
Ggplot2 Two-Line Label With Expression
Multiply Rows of Matrix by Vector
Dplyr: Nonstandard Column Names (White Space, Punctuation, Starts With Numbers)
R Ifelse to Replace Values in a Column
Count Nas Per Row in Dataframe
Return Elements of List as Independent Objects in Global Environment