R-循环功能以1为增量 [英] R - looping function in increments of 1

查看:72
本文介绍了R-循环功能以1为增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能:

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))

哪个会产生:

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.

是否有一种以+ 1为增量循环的方式,因此时间点每次增加1,并且保存为的数据帧的名称也每次增加1.

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.

期望

##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)

推荐答案

这是问题第一部分的答案:

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))
}

这篇关于R-循环功能以1为增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆