reshape
已被 取代reshape2
,后者更快且内存效率更高。它还具有colsplit
按您的意愿执行的功能
library(reshape2)
# melt (using site, longitude and latitude as ids)
rich.melt <- melt(site_richness, id = 1:3)
# create a variable without `site_richness_` prefix
rich.melt$v2 <- rich.melt$variable
levels(rich.melt$v2) <- gsub('^site_richness_','',levels(rich.melt$v2))
# use colsplit to split on `_` and combine with the newest data
rich.melt2 <- cbind(rich.melt, colsplit(rich.melt$v2, pattern = '_', names = c('scenario','year')))
# drop unwanted columns and reorder
rich.melt.final <- rich.melt2[, c("Site", "Longitude", "Latitude",
"scenario", "year", "species_richness")]
head(rich.melt.final)
Site Longitude Latitude scenario year species_richness
# 1 ABSF -78.6492 37.4343 2.6 2050 4
# 2 ALLSP -74.1487 40.1481 2.6 2050 31
# 3 ANSF -71.9341 42.7743 2.6 2050 49
# 4 ARSP -68.0148 46.6067 2.6 2050 19
# 5 BAXP -68.8520 46.1645 2.6 2050 23
# 6 BBSP -71.3822 43.1643 2.6 2050 35