我正在尝试开发一个if else语句,以应用于下面的data.frame。以下是我想要解释的情况:
如果你对最好的方法有任何想法的话,我会非常感激的。当有多种条件的时候,我不知道该从哪里开始。
示例df:
名称<- c("t1“、"t2”、"t3“、"t3”) 值<- c(1.7、2.6、3.2、4.1、1.8、3.4、2.4、3.6、4.0、1.9、2.3) 年<- c(2000、2001、2002、2003、2001、2002、2003、2000、2001、2002、2003) YearLimitA <- c(2001年、2001年、2001年、2001年、2002年、2002年、2002年、2002年、2002年、2002年、2002年、2002年) YearLimitB <- c(2002年、2002年、2002年、2002年、2002年、2002年、2001年、2001年、2001年、2001年) df <- data.frame(名称、值、年份、YearLimitA、YearLimitB)
if after语句之后的预期df:
名称<- c("t1“、"t2”、"t2“、"t3”、"t3“、"t3") 值<- c(1.3、3.2、4.1、3.4、2.4、2.0、1.9、2.3) 年<- c(2001、2002、2003、2002、2003、2001、2002、2003) YearLimitA <- c(2001年、2001年、2001年、2002年、2002年、2002年、2002年、2002年) YearLimitB <- c(2002年、2002年、2002年、2002年、2001年、2001年、2001年) df2 <- data.frame(名称、值、年份、YearLimitA、YearLimitB)
发布于 2014-07-15 19:40:20
试试这个:
df <- df[df$Year >= pmin(df$YearLimitA, df$YearLimitB),]
df$Value <- with(df, ifelse(Year>=pmax(YearLimitA, YearLimitB), Value, Value/2))首先,我们只保留Year至少与YearLimitA和YearLimitB的最小值一样大的行。然后,如果Year至少与这两个变量的成对最大值一样大,则保留该值。如果没有,则除以2。
这会产生
Name Value Year YearLimitA YearLimitB
2 t1 1.3 2001 2001 2002
3 t1 3.2 2002 2001 2002
4 t1 4.1 2003 2001 2002
6 t2 3.4 2002 2002 2002
7 t2 2.4 2003 2002 2002
9 t3 2.0 2001 2002 2001
10 t3 1.9 2002 2002 2001
11 t3 2.3 2003 2002 2001all.equal(df2, df, check.attributes=F)给了TRUE。
发布于 2014-07-15 19:44:08
这里有一个方法:
# sort years
rangeYear <- apply(df[c("YearLimitA", "YearLimitB")], 1, range)
# remove colums
idx <- df$Year >= rangeYear[1, ]
df2 <- df[idx, ]
# change values
df2 <- transform(df2, Value = Value / (1 + (Year < rangeYear[2, ][idx])))结果:
Name Value Year YearLimitA YearLimitB
2 t1 1.3 2001 2001 2002
3 t1 3.2 2002 2001 2002
4 t1 4.1 2003 2001 2002
6 t2 3.4 2002 2002 2002
7 t2 2.4 2003 2002 2002
9 t3 2.0 2001 2002 2001
10 t3 1.9 2002 2002 2001
11 t3 2.3 2003 2002 2001https://stackoverflow.com/questions/24766185
复制相似问题