批量为变量分配名称时,R Functionals 不起作用
R Functionals does not work when batch assigning names to variables
我想使用泛函批量为 csv 数据文件分配名称,我测试了泛函,包括 Map
、mapply
、lapply
和函数 assign
替换 <-
,但是所有这些函数都不起作用,只有传统的 for 循环起作用,有人能解释一下吗?提前致谢!
这是我的代码:
allData <- c("Actinomyces.csv", "Bacteria.csv", "COD.csv", "Fungi.csv", "NH3.csv", "NO2.csv", "NO3.csv", "TN.csv", "TP.csv")
#CSV files in the working path
csvs <- lapply(allData, read.csv)
#Store data frames into a list
nameList <- c("Actinomyces", "Bacteria", "COD", "Fungi", "NH3", "NO2", "NO3", "TN", "TP")
lapply(c(1:9), function(i){assign(nameList[i], csvs[[i]])})
#Doesn't work
Map(assign, nameList, csvs)
#Doesn't work either
mapply(assign, nameList, csvs)
#Doesn't work again
for (i in 1:9){
assign(nameList[i], csvs[[i]])
}
#Only this works
这里有两种基本的 R 方式:
junk <- Map("assign", nameList, csvs, MoreArgs = list(.GlobalEnv))
list2env(setNames(csvs, nameList), .GlobalEnv)
此任务的更典型的 R 习语是从这里开始:
csvs <- lapply(allData, read.csv)
此时您的数据已很好地存储在列表中。如果你想要一个命名列表,你可以简单地做:
nameList <- c("Actinomyces", "Bacteria", "COD", "Fungi", "NH3", "NO2", "NO3", "TN", "TP")
csvs <- setNames(csvs, nameList)
然后您可以通过 csvs[["COD"]]
按名称引用任何数据集,例如。
我想使用泛函批量为 csv 数据文件分配名称,我测试了泛函,包括 Map
、mapply
、lapply
和函数 assign
替换 <-
,但是所有这些函数都不起作用,只有传统的 for 循环起作用,有人能解释一下吗?提前致谢!
这是我的代码:
allData <- c("Actinomyces.csv", "Bacteria.csv", "COD.csv", "Fungi.csv", "NH3.csv", "NO2.csv", "NO3.csv", "TN.csv", "TP.csv")
#CSV files in the working path
csvs <- lapply(allData, read.csv)
#Store data frames into a list
nameList <- c("Actinomyces", "Bacteria", "COD", "Fungi", "NH3", "NO2", "NO3", "TN", "TP")
lapply(c(1:9), function(i){assign(nameList[i], csvs[[i]])})
#Doesn't work
Map(assign, nameList, csvs)
#Doesn't work either
mapply(assign, nameList, csvs)
#Doesn't work again
for (i in 1:9){
assign(nameList[i], csvs[[i]])
}
#Only this works
这里有两种基本的 R 方式:
junk <- Map("assign", nameList, csvs, MoreArgs = list(.GlobalEnv))
list2env(setNames(csvs, nameList), .GlobalEnv)
此任务的更典型的 R 习语是从这里开始:
csvs <- lapply(allData, read.csv)
此时您的数据已很好地存储在列表中。如果你想要一个命名列表,你可以简单地做:
nameList <- c("Actinomyces", "Bacteria", "COD", "Fungi", "NH3", "NO2", "NO3", "TN", "TP")
csvs <- setNames(csvs, nameList)
然后您可以通过 csvs[["COD"]]
按名称引用任何数据集,例如。