我是 stata 的新手,这是我第一次使用它:( 我有在科威特市场经营 10 年的公司的数据集,从 2013 年到 2022 年,每年都在不同的 Excel 文件中。所以我总共有 10 个 excel 文件,我将它们保存在一个文件夹中,文件夹 bath "C:\Users oura\OneDrive\Desktop\project excel" excel文件名: 2013 2014 2015年 2016年 2017年 2018 2019 2020 2021年 2022
那么我如何将 10 个 excel 文件导入 Stata 并确保 Stata 正在读取从 2013 年到 2022 年的数据。
我应该使用什么代码?
我尝试了几个代码但没有任何效果
// Set the working directory to the folder where your Excel files are saved
cd "C:\Users\noura\OneDrive\Desktop\project excel"
// Loop over each year and import the corresponding Excel file into Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using "`file'.xlsx"
}
// Sort the data by year
sort year
你非常接近解决方案。干得好,这是您第一次使用 Stata。
你的代码中的问题是
clear
在
import excel "`file'.xlsx", firstrow clear
清除当前内存中的所有数据。所以在每个循环中你都删除了所有以前的年份。在我对示例代码的修改中,我设置了一个临时文件,用于在每个循环结束时将数据保存到其中。然后将您的年份数据附加到该数据集。
// Set the working directory to the folder where your Excel files are saved
cd "C:\Users\noura\OneDrive\Desktop\project excel"
clear
tempfile allyears
save `allyears', emptyok
// Loop over each year and import the corresponding Excel file into Stata
foreach file of varlist 2013/2022 {
import excel "`file'.xlsx", firstrow clear
gen year = "`file'"
append using `allyears'
save `allyears', replace
}
// Sort the data by year
sort year