如何有条件地更新R中的表?
我的桌子看起来像这样:如何有条件地更新R中的表?,r,R,我的桌子看起来像这样: # Year Month WaterYear # 1993 3 # 2000 4 # 2013 10 # 2015 6 # 2000 7 # 2008 12 # 2008 9 # 2012 10 # 2000 11 # 2000 12 我试图通过计算W
# Year Month WaterYear
# 1993 3
# 2000 4
# 2013 10
# 2015 6
# 2000 7
# 2008 12
# 2008 9
# 2012 10
# 2000 11
# 2000 12
我试图通过计算WaterYear等于Year+1来更新此表,其中月份范围为10月至12月
我正在研究R,希望找到最简单的方法使其工作。Simple
ifelse
函数会起作用。
从你的数据
# Create data
Year <- c(1993, 2000, 2013, 2015, 2000, 2008, 2008, 2012, 2000, 2000)
Month <- c(3, 4, 10, 6, 7, 12, 9 ,10, 11, 12)
WaterYear <- rep("",length(Year))
dat <- data.frame(Year, Month, WaterYear)
# If month is greater or equal to 10 change it to Year +1,
# otherwise keep it as it is
dat$WaterYear <- ifelse(dat$Month >=10, Year+1, WaterYear)
我们也可以这样做
i1 <- dat$Month >=10
dat$WaterYear[i1] <- dat$Year[i1] + 1
dat
# Year Month WaterYear
#1 1993 3
#2 2000 4
#3 2013 10 2014
#4 2015 6
#5 2000 7
#6 2008 12 2009
#7 2008 9
#8 2012 10 2013
#9 2000 11 2001
#10 2000 12 2001
请尝试
哪个(cond,arr.ind=TRUE)
,其中cond
是您的状况。非常感谢。这是我正在寻找的功能。
i1 <- dat$Month >=10
dat$WaterYear[i1] <- dat$Year[i1] + 1
dat
# Year Month WaterYear
#1 1993 3
#2 2000 4
#3 2013 10 2014
#4 2015 6
#5 2000 7
#6 2008 12 2009
#7 2008 9
#8 2012 10 2013
#9 2000 11 2001
#10 2000 12 2001
library(data.table)
setDT(dat)[Month >=10, WaterYear := as.character(Year + 1)]