用于更新data.frame的循环

时间:2017-08-02 19:52:40

标签: r for-loop

我正在尝试编写一个“for循环”来迭代更新我的R数据帧。

这是我的代码:

datalist = list()

for (i in 1:5) { 
dat <- data.frame(ID=LETTERS[seq( from = 1, to = 20 )],nutrition=rnorm(20, mean=50, sd=10),
                Stage=c(rep("A1",5), rep("B1",15)))
dat$ADG<-dat$nutrition*0.05
dat$M_weight<-dat$nutrition*0.5+dat$ADG*100
dat$Age<-dat$M_weight*1.1+dat$ADG*0.6
dat$Stage<-as.character(dat$Stage)
dat$Stage[dat$ADG>=3]<-"C1" 
dat$i <- i  # maybe you want to keep track of which iteration produced it?
datalist[[i]] <- dat # add it to your list    # 



}

big_data = do.call(rbind, datalist)

从迭代2开始,如果ADG等于或大于3,我想将“Stage”更新为“C1”,但这不适用于迭代1.

非常感谢你!我感谢任何回复!

1 个答案:

答案 0 :(得分:1)

我认为您需要recursive函数而不是迭代函数

您的数据stringsAsFactors=F

dat <- data.frame(ID=LETTERS[seq( from = 1, to = 20 )], nutrition=rnorm(20, mean=50, sd=10), Stage=c(rep("A1",5), rep("B1",15)), stringsAsFactors=F)

tidyversedplyr动词使用purrr

library(tidyverse)
special <- function( dat, counter, end ) { 
                 dat1 <- dat %>%
                       mutate(ADG = nutrition*0.05) %>%
                       mutate(M_weight = nutrition*0.5 + ADG*100) %>%
                       mutate(Age = M_weight*1.1 + ADG*0.6) %>%
                       mutate(Stage = ifelse( ADG >= 3, "C1", Stage )) %>%
                       mutate(i=counter)
                 if (counter < end) {
                       special(dat1, counter+1, end) 
                 } else {
                       return(dat1)
                 }                   
            }

desired <- map_df(2:5, ~special(dat,1,.x))

head(desired)

   ID nutrition Stage      ADG M_weight      Age i
1   A  47.17826    A1 2.358913 259.4804 286.8438 2
2   B  64.55988    C1 3.227994 355.0794 392.5241 2
3   C  52.29020    A1 2.614510 287.5961 317.9244 2
4   D  59.96544    A1 2.998272 329.8099 364.5899 2

如果这不是您期望的输出,请告诉我