【发布时间】:2018-05-24 22:14:03
【问题描述】:
我有一个如下所示的数据框:
YEAR X1990_lu X2000_lu X2010_lu soil water
1 1990 215.0310 215.0310 215.0310 3.588198 5.287578
2 2007 415.3221 415.3221 415.3221 8.094746 5.788305
3 1994 263.5908 263.5908 263.5908 4.680792 5.408977
4 2010 453.2070 453.2070 453.2070 8.947157 5.883017
5 2012 476.1869 476.1869 476.1869 9.464206 5.940467
6 1981 118.2226 118.2226 118.2226 1.410008 5.045556
7 1998 311.2422 311.2422 311.2422 5.752949 5.528105
8 2011 456.9676 456.9676 456.9676 9.031771 5.892419
9 1999 320.5740 320.5740 320.5740 5.962915 5.551435
10 1995 282.6459 282.6459 282.6459 5.109533 5.456615
11 2013 482.7333 482.7333 482.7333 9.611500 5.956833
12 1995 281.3337 281.3337 281.3337 5.080007 5.453334
13 2003 371.0283 371.0283 371.0283 7.098136 5.677571
14 2000 329.0534 329.0534 329.0534 6.153701 5.572633
15 1983 141.1699 141.1699 141.1699 1.926322 5.102925
如果列名的相应数字部分大于该行的 YEAR 值,我需要将名称中带有 _lu 的任何列设置为 NA。我可以使用下面的代码对每个单独的列执行此操作,其中我提取_lu 列名的数字部分并制作一个数字向量以与 YEAR 进行比较。但是,这可以通过使用 apply 或可能的 map 语句对所有列完成吗?
## make example data
set.seed(123)
soil <- runif(15,1,10)
set.seed(123)
water <- runif(15,5,6)
set.seed(123)
X1990_lu <- runif(15,100,500)
set.seed(123)
X2000_lu <- runif(15,100,500)
set.seed(123)
X2010_lu <- runif(15,100,500)
set.seed(123)
YEAR <- as.integer(runif(15,1980,2015))
data <- data.frame(YEAR, X1990_lu, X2000_lu, X2010_lu, soil, water)
# extract the column indices of the landuse columns
lucolsind <- grep("_lu", names(data))
# remove the x from each landuse column name
colnames(data)[lucolsind] <- substring(names(data[,lucolsind]), 2)
# get the column names
lucolnms <- names(data[,lucolsind])
# get the column names as a split list
lucolnms_lst <- strsplit(names(data[,lucolsind]), c("_"))
# extract just the year indicator
luyears <- unlist(lapply(lucolnms_lst, `[[`, 1))
# set the first LU column to NA where year is less than the lu year
data[,lucolsind[1]] <- ifelse(data$YEAR < luyears[1], NA, data[,lucolsind[1]])
这是处理第一个_lu 列后的样子
YEAR 1990_lu 2000_lu 2010_lu soil water
1 1990 215.0310 215.0310 215.0310 3.588198 5.287578
2 2007 415.3221 415.3221 415.3221 8.094746 5.788305
3 1994 263.5908 263.5908 263.5908 4.680792 5.408977
4 2010 453.2070 453.2070 453.2070 8.947157 5.883017
5 2012 476.1869 476.1869 476.1869 9.464206 5.940467
6 1981 NA 118.2226 118.2226 1.410008 5.045556
7 1998 311.2422 311.2422 311.2422 5.752949 5.528105
8 2011 456.9676 456.9676 456.9676 9.031771 5.892419
9 1999 320.5740 320.5740 320.5740 5.962915 5.551435
10 1995 282.6459 282.6459 282.6459 5.109533 5.456615
11 2013 482.7333 482.7333 482.7333 9.611500 5.956833
12 1995 281.3337 281.3337 281.3337 5.080007 5.453334
13 2003 371.0283 371.0283 371.0283 7.098136 5.677571
14 2000 329.0534 329.0534 329.0534 6.153701 5.572633
15 1983 NA 141.1699 141.1699 1.926322 5.102925
【问题讨论】:
标签: r