我有以下MWE:
N <- 84 #Number of datasets to pull data from
dates <- c("2010.01", "2010.02", "2010.03", "2010.04", "2010.05", "2010.06", "2010.07", "2010.08",
"2010.09", "2010.10", "2010.11", "2010.12", "2011.01", "2011.02", "2011.03", "2011.04", "2011.05",
"2011.06", "2011.07", "2011.08", "2011.09", "2011.10", "2011.11", "2011.12", "2012.01", "2012.02",
"2012.03", "2012.04", "2012.05", "2012.06", "2012.07", "2012.08", "2012.09", "2012.10", "2012.11",
"2012.12", "2013.01", "2013.02", "2013.03", "2013.04", "2013.05", "2013.06", "2013.07", "2013.08",
"2013.09", "2013.10", "2013.11", "2013.12", "2014.01", "2014.02", "2014.03", "2014.04", "2014.05",
"2014.06", "2014.07", "2014.08", "2014.09", "2014.10", "2014.11", "2014.12", "2015.01", "2015.02",
"2015.03", "2015.04", "2015.05", "2015.06", "2015.07", "2015.08", "2015.09", "2015.10", "2015.11",
"2015.12", "2016.01", "2016.02", "2016.03", "2016.04", "2016.05", "2016.06", "2016.07", "2016.08",
"2016.09", "2016.10", "2016.11", "2016.12") #list of all dates to loop through
A <- list()
for (k in seq_along(dates)) {
A[[k]] <- read_excel(paste0("~/R/data.", dates[k], ".xlsx"), range = "B3:EO94")
}
data <- array(unlist(A), dim=c(91,144,84)) #3-dimensional array
####Problem here####
countries <- c("Can", "US")
coord <- c("15,34", "23,28")
long <- c("34", "28")
lat <- c("15", "23")
for (c in seq_along(countries)) {
for (i in seq_along(lat)) {
for (j in seq_along(long)) {
nam <- sprintf("ci%d%d", c, i)
assign(nam, data[i,j,])
}}}
我基本上是试图创建两个向量,我可以分别以Can <- data[15,34,]
和编写US <- data[23,28,]
。我的问题在于我想尝试写入数据[[x,y],]以识别循环值内的逗号。我想知道是否有解决办法?我不认为有一个单独的i
并j
循环通过会起作用,因为它将使4个变量变为否?
我可以单独进行操作,但是我有将近100个国家/地区这样做,因此,我期待着循环。
我们可以将循环修改为
for (c in seq_along(countries)) {
for (i in seq_along(lat)) {
for (j in seq_along(long)) {
#nam <- sprintf("s%s%s", countries[c], lat[i], long[j])
#Or with `paste`
nam <- paste0(countries[c], lat[i], long[j])
assign(nam, data[as.integer(lat[i]),as.integer(long[j]),])
}}}
如果"[c]"
在中进行paste
,则不会进行任何插值。它只是文字字符“ [c]”。我们可以用sprintf
..
nam <- sprintf("ci%d%d", c, i)
..
或搭配 glue::glue
..
nam <- as.character(glue::glue("ci{c}{i}"))
..
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句