我有一段时间以来的土地使用数据,并试图编写一个逻辑函数,返回一个观察(这是一块小块土地)是否已从草地变为农田,并一直待在农田上。下面是我数据中的小样本。
crop2 <- read.table(text="
OBS 2003 2004 2005 2006 2007 2008 changes
494136 Grassland Grassland Grassland Developed Cropland Grassland 2
825726 Developed Developed Developed Grassland Grassland Grassland 1
500019 Forest Forest Forest Forest Forest Grassland 1
587587 Cropland Cropland Cropland Cropland Cropland Cropland 0
524302 Grassland Grassland Cropland Cropland Cropland Cropland 1
158075 Cropland Cropland Cropland Cropland Cropland Cropland 0
",header=TRUE,check.names=FALSE)在此数据示例中,该函数将只返回带true的第二个到最后一个观察结果。我试过使用各种函数和if-语句,但无法正确编码(部分原因是从农田到草地的转换可能在任何一年发生。我编写了这个函数来查找是否发生了更改(它是更改变量),但需要提取更多的信息,而不是是否发生更改:长度(as.character(crop2x,))。
我的数据文件名为crop2,每一列都以年份命名。变量为5个层次的因子。谢谢你的帮助。
发布于 2014-04-09 22:54:31
使用rle
apply(
crop2[2:7],
1,
function(x) all(tail(rle(x)$values,2) == c("Grassland","Cropland"))
)
#[1] FALSE FALSE FALSE FALSE TRUE FALSE一个函数是apply-ed,它跨越由子集crop2[2:7]定义的年度数据的每一行(MARGIN=1)。
rle(x)$values返回土地使用变化的顺序,例如第5行:
# 2004 2008
#"Grassland" "Cropland"将其包装在tail(...,2)中只会给出最后两个使用之间的更改,在这个实例中,这又是相同的数据:
# 2004 2008
#"Grassland" "Cropland"all(... = c("Grassland","Cropland"))位只是测试直接来自"Grassland" (在本例中为TRUE )之后,土地使用是否以"Cropland"的形式结束。
https://stackoverflow.com/questions/22975303
复制相似问题