cost_a0 150200380 0hiegh em 00
所以我有一个复杂的问题,我必须模拟状态随时间的变化(25年)我的数据框架如下所示:
edu对于第一个条件
试试这个for(x in 1:nrow(df))
if(df$statu[x] == "unem" & df$sal_a[x] > df$cost_a[x])
{
df$statu[x] <- "em"
df$age[x] <- df$age[x] + 1
df$exp_y[x] <- df$exp_y[x] +1
df$sal[x] <- df$sal_a[x]*(1+0.19*df$exp_y[x])
df$cost[x] <- df$cost_a[x]
df$sal_a[x] <- 0
df$cost_a[x] <- 0
}
用于第二个条件
for(x in 1:nrow(df))
if(df$statu[x] == "em" & df$sal[x] < df$cost[x])
{
df$statu[x] <- "unem"
df$age[x] <- df$age[x] + 1
df$sal_a[x] <- df$sal[x]
df$cost_a[x] <- df$cost[x]
df$exp_y[x] <- df$exp_y[x]
df$sal[x] <- 0
df$cost[x] <- 0
}
df <- structure(list(age = c(27, 21, 25, 24, 36, 42), sex = c("f",
"m", "m", "m", "f", "f"), edu = c("no", "low", "low", "no", "hiegh",
"low"), statu = c("unem", "em", "em", "em", "em", "em"), exp_y = c(2,
1, 3, 10, 18, 17), sal = c(0, 341.53, 541.65, 380, 684, 646),
cost = c(0, 150, 200, 150, 300, 245), sal_a = c(76, 0, 0,
0, 0, 0), cost_a = c(100, 0, 0, 0, 0, 0)), row.names = c(NA,
-6L), class = "data.frame")
输出age sex edu statu exp_y sal cost sal_a cost_a
1 27 f no unem 2 0.00 0 76 100
2 21 m low em 1 341.53 150 0 0
3 25 m low em 3 541.65 200 0 0
4 24 m no em 10 380.00 150 0 0
5 36 f hiegh em 18 684.00 300 0 0
6 42 f low em 17 646.00 245 0 0
你可以试试:
# Number of years
y <- 25
# Create a list
evol <- list()
# Make "y" copies of your df
for (i in 1:y){evol[[i]] <- df}
# At each step (strting in the second element) evaluate the changes
for (i in 2:y){
# Logical vector (including the positions of rows to change)
v.logic <- evol[[i-1]]$statu=="unem" & evol[[i-1]]$sal_a> evol[[i]]$cost_a
v.logic2 <- evol[[i-1]]$statu=="em" & evol[[i-1]]$sal<evol[[i-1]]$cost
# Values to change
# Fist condition
evol[[i]][v.logic,"age"] <- evol[[i-1]][v.logic,"age"] + 1
evol[[i]][v.logic,"exp_y"] <- evol[[i-1]][v.logic,"exp_y"] + 1
evol[[i]][v.logic,"sal"] <- evol[[i-1]][v.logic,"sal_a"]*(1+0.19*evol[[i-1]][v.logic,"exp_y"])
evol[[i]][v.logic, "cost"] <- evol[[i-1]][v.logic,"cost_a"]
evol[[i]][v.logic, "sal_a"] <- 0
evol[[i]][v.logic, "cost_a"] <- 0
# Second condition
evol[[i]][v.logic2,"statu"] <- "unem"
evol[[i]][v.logic2, "age"] <- evol[[i-1]][v.logic2, "age"] + 1
evol[[i]][v.logic2, "sal_a"] <- evol[[i-1]][v.logic2, "sal"]
evol[[i]][v.logic2, "cost_a"] <- evol[[i-1]][v.logic2, "cost"]
evol[[i]][v.logic2, "sal"] <- 0
evol[[i]][v.logic2, "cost"] <- 0
}
它将产生一个列表,其中第i个元素表示第i年的表。