R - looping function in increments of 1

…衆ロ難τιáo~ 提交于 2021-01-28 03:44:37

问题


I have the following function:

position_tab <- filter(Tall, Time_point == 2) %>% group_by(Object) %>%  summarise(minimum = min(Pixel_pos), maximum = max(Pixel_pos))
position_tab_2 <- mutate(position_tab, midpoint = minimum + ((maximum - minimum)/2))

Which produces:

Object minimum maximum midpoint
1         4      22       13
2         39     85       62
etc..

This is filtering for a given timepoint, and creating a new dataframe with the midpoint variable added.

Is there a way to loop this in increments of + one, so that the timepoint increases by one each time and the name of the dataframe it saves as, is also increased by one each time.

Expectation

##loop one:
position_tab <- filter(Tall, Time_point == 1) %>% group_by(Object) %>%  summarise(minimum = min(Pixel_pos), maximum = max(Pixel_pos))
position_tab_1 <- mutate(position_tab, midpoint = minimum + ((maximum - minimum)/2))

##loop two:
position_tab <- filter(Tall, Time_point == 2) %>% group_by(Object) %>%  summarise(minimum = min(Pixel_pos), maximum = max(Pixel_pos))
position_tab_2 <- mutate(position_tab, midpoint = minimum + ((maximum - minimum)/2))

##continues looping until max(Time_point)

回答1:


It is an answer for the first part of your question :

df <- structure(list(Pixel_pos = c(4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 
12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 39L), 
Time_point = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1), Intensity = c(1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), Object = c(2666L, 2666L, 
2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 
2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2666L, 2668L
)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame"
))
time_points <- max(df$Time_point)
# stock data.frame
list_df <- vector(mode = "list", time_points)
# name list object
names(list_df) <- paste("position_tab", 1:time_points, sep ="_")
for(t in 1:time_points){
    # apply your filter
    list_df[[t]] <- filter(df, Time_point == t) %>% group_by(Object) %>% 
        summarise(minimum = min(Pixel_pos), maximum = max(Pixel_pos)) %>%
        mutate(midpoint = minimum + ((maximum - minimum)/2))
}


来源:https://stackoverflow.com/questions/62641948/r-looping-function-in-increments-of-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!