From excel to dta

Install XLS2DTA package

ssc install xls2dta,replace

The results are as follows:

checking xls2dta consistency and verifying not already installed...
all files already exist and are up to date.

Installed

Convert XLSX files to DTA files

xls2dta:import excel no_miss.xlsx,first case(lower)

The first case here refers to the first line of Excel as a variable name when converting Excel to the DTA format.
result:

(18 vars, 3,317 obs)
file d:academysharing_codedatano_miss.dta saved

Use DTA files

use no_miss.dta

Enter the browsing data and edit the data, and further analyze the data

Содержание

  1. Русские Блоги
  2. Несколько методов импорта данных Stata
  3. оглавление
  4. 1. Метод 1: Ctrl + C / Ctrl + V (применимо, когда объем данных небольшой)
  5. 2. Метод 2. Импортируйте файл Excel напрямую (применимо, если файл большой).
  6. 3. Способ 3. Дважды щелкните файл dta, чтобы открыть его с помощью Stata.
  7. 4. Метод 4: импортировать сохраненный файл в Stata.
  8. 5. Метод 5. Введите команду использования.
  9. Интеллектуальная рекомендация
  10. Проверка полномочий на основе JWT и фактические боевые учения
  11. [Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов
  12. Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)
  13. [Серия исходного кода Java] строка (2) Проблема нового, а не новой
  14. 05-Vue News Mobile Project
  15. Вам также может понравиться
  16. 1008 Рассматривая задача Element Element Cycle (20 баллов)
  17. Linux centos7 виртуальная машина установить Docker (5) —. Netcore
  18. Разработать интерфейс мониторинга состояния здоровья
  19. [Реабилитация] #C Language Array Joseph Проблема
  20. From excel to dta
  21. 1 item has been added to your cart.
  22. Stata/MP4 Annual License (download)
  23. Stata: Data Analysis and Statistical Software
  24. How do I get information from Excel into Stata?
  25. 1. A rule to remember
  26. 2. How to get information from Excel into Stata
  27. 3. Other methods for transferring information
  28. 3.1 Copy and paste
  29. 3.2 import delimited command
  30. 3.3 ODBC and odbc load
  31. 4. Copying a Stata graph into Excel or any other package
  32. 5. Common problems
  33. 5.1 Nonnumeric characters
  34. 5.2 Spaces
  35. 5.3 Cell formats
  36. 5.4 Variable names
  37. 5.5 Missing rows and columns
  38. 5.6 Leading zeros
  39. 5.7 Filename and folder

Русские Блоги

Несколько методов импорта данных Stata

оглавление

1. Метод 1: Ctrl + C / Ctrl + V (применимо, когда объем данных небольшой)

2. Метод 2. Импортируйте файл Excel напрямую (применимо, если файл большой).

3. Способ 3. Дважды щелкните файл dta, чтобы открыть его с помощью Stata.

4. Метод 4: импортировать сохраненный файл в Stata.

  • Используйте SPSS, чтобы открыть сохраненный файл, SPSS может вывести файл в формат Stata
  • Выберите сохранить, чтобы получить файл dta, дважды щелкните, чтобы открыть данные с помощью Stata

5. Метод 5. Введите команду использования.

Войдите в область команд Stata

Вы можете использовать файл dta.Как правило, удобнее открыть папку напрямую и дважды щелкнуть ее, чтобы открыть.

  • Stata не обеспечивает операций отмены, а несохраненные данные хранятся в области памяти. Используйте команду clear, чтобы удалить данные в области памяти. Обратите внимание на своевременное сохранение и резервное копирование при выполнении операций редактирования данных.
  • Stata чувствительна к регистру.

Интеллектуальная рекомендация

Проверка полномочий на основе JWT и фактические боевые учения

Предисловие: Большинство систем, за исключением большинства финансовых систем, требуют строгой системы безопасности (такой как shiro), общие требования к безопасности системы не очень высоки, требуетс.

[Android Development Fast Getsing] Запустите стойку регистрации приложения для подсказки для тостов

1. Реализуйте переднюю и заднюю часть приложения Цель:Чтобы снять риск захвата интерфейса Android, сообщите пользователям, что приложение работает в фоновом режиме. Обычно нажимает клавишу Home, чтобы.

Установите Raspberry Pi из Raspberry Pi в беспроводной маршрутизатор (Wi -Fi Hotspot AP, RTL8188CUS Chip)

Эта статья основана на USB Wireless Network Card (RTL8188CUS Chip), приобретенной на определенном востоке, чтобы создать беспроводные горячие точки. Первоначально я хотел сделать один сценарий. Просто.

[Серия исходного кода Java] строка (2) Проблема нового, а не новой

Серия строк: 【Серия исходного кода Java】 строка (1) под анализом базовой структуры [Серия исходного кода Java] строка (2) Проблема нового, а не новой [Серия исходного кода Java] Строка (3) Общий анали.

05-Vue News Mobile Project

1 Javascri не добавляет при добавлении толстой кишки При получении и изменении атрибутов реквизит плюс this. $router.push( ) 2 Axios Установка и использование Цитата в main.js 2.1axios, чтобы отправит.

Вам также может понравиться

1008 Рассматривая задача Element Element Cycle (20 баллов)

Массив A содержит n (> 0) целое число, не позволяя использовать дополнительные массивы, чтобы повернуть каждое целое число в положение правого m (≥0), данные в (A 0) A1 ⋯ A N-1) (An-M ⋯ A N-1 A .

Linux centos7 виртуальная машина установить Docker (5) —. Netcore

Текущая версия: версия Docker (например, Docker 17.03.2) .netcore версия 3.1 1 Постройте зеркало 2 запустить зеркало 3 Доступ Введите контейнер Nginx: Посещение в контейнере Выйдите из контейнера, что.

Разработать интерфейс мониторинга состояния здоровья

1. Требование Интерфейс должен содержать логическую обработку и чтение базы данных. 2. Реализация 1) Разработать доступ к интерфейсу к базе данных, успешный доступ, код статуса возврата 200, ненормаль.

[Реабилитация] #C Language Array Joseph Проблема

Я не двигал код в течение года. Теперь мой мозг не хорош, я использовал глупость, чтобы решить проблему Йозефа кольца. Написание здесь является запись, которая спасает свой собственный беспорядок. Воп.

Источник

From excel to dta

Строго говоря, мне нужно конвертировать только один файл: cpi-98-18.dta в https://www.researchgate.net/post/Co. if_you_have_it
В одном месте прочитал, что самый простой способ – это с помощью программы Stata, но не смог её найти.
В списке программ для открытия dta – файлов https://www.filetypeadvisor.com/ru/extension/dta увидел даже Microsoft Office. Но никакие его программы у меня делать это не хотели.
В https://stackoverflow.com/questions/. stata-software приведёно много других разных советов. В частности, программа SPSS, но она тоже что-то не пошла. Попробовал скачать там и некоторые другие рекомендуемые программы, но не смог найти … Целый день сегодня с этим провозился и решил написать на форум.

Может, кто знает конкретную программу, которая свободно лежит в сети и которую там можно взять и использовать для конвертации? Или, может, кто просто поможет конвертировать упомянутый файл (всего то — один)?


__________________
Есть две бесконечные вещи, Вселенная и глупость.
Впрочем, на счет Вселенной, я не уверен

Какая-то программа работы с со статистикой.

Родная, судя по всему, к таким («dta») файлам — это программа stata. Хотя, это условно: похоже, и другие программы с этим расширением работают как с родным.
Я бы тоже хотел получше узнать что за файл, но, судя по тому, что откуда я его скачал — было много благодарностей за файл и никто не спросил (кроме меня в самом конце) что это за фал — это какой-то стандартный, в каких-то «статистических кругах» формат.
В сети пишут, что с форматом работает программа stata так, что склоняюсь к выводу, что изначально он для этой программы и был создан. Но в свободном доступе в сети найти её не смог.

Источник

1 item has been added to your cart.

Stata/MP4 Annual License (download)

Stata: Data Analysis and Statistical Software

How do I get information from Excel into Stata?

Title Converting other format files into Stata dataset files
Author Nicholas J. Cox, Durham University, UK

1. A rule to remember
2. How to get information from Excel into Stata
3. Other methods for transferring information
3.1 Copy and paste
3.2 import delimited command
3.3 ODBC and odbc load
4. Copying a Stata graph into Excel or any other package
5. Common problems
5.1 Nonnumeric characters
5.2 Spaces
5.3 Cell formats
5.4 Variable names
5.5 Missing rows and columns
5.6 Leading zeros
5.7 Filename and folder

1. A rule to remember

Stata expects one matrix or table of data from one sheet, with at most one line of text at the start defining the contents of the columns.

2. How to get information from Excel into Stata

Stata can directly import data from Excel (both .xls and .xlsx) files.

Select File > Import > Excel Spreadsheet from Stata’s menus.

Also, see import excel for more information on importing Excel spreadsheets directly into Stata.

3. Other methods for transferring information

3.1 Copy and paste

Using your Windows or Mac computer,

  1. Start Excel.
  2. Enter data in rows and columns or read in a previously saved file.
  3. Highlight the data of interest, and then select Edit and click Copy.
  4. Start Stata and open the Data Editor (type edit at the Stata dot prompt).
  5. Paste data into editor by selecting Edit and clicking Paste.

3.2 import delimited command

The following section is based on material originally written by James Hardin, University of South Carolina, and Ted Anagnoson, California State Los Angeles.

  1. Launch Excel and read in your Excel file.
  2. Save as a text file (tab delimited or comma delimited) by selecting File and clicking Save As. If the original filename is filename.xls, then save the file under the name filename.txt or filename.csv. (Use the Save as type list—specifying an extension such as .txt is not sufficient to produce a text file.)
  3. Quit Excel if you wish.
  4. Launch Stata if it is not already running. (If Stata is already running, then either save or clear your current data.)
  5. In Stata, type import delimited usingfilename.ext, where filename.ext is the name of the file that you just saved in Excel. Give the complete filename, including the extension.
  6. In Stata, type compress.
  7. Save the data as a Stata dataset using the save command.

3.3 ODBC and odbc load

The following section is provided by Kevin Turner, StataCorp.

  1. You will have to download and install an Excel ODBC driver from Microsoft’s website to work with Excel files.
  2. Launch Stata.
  3. List the ODBC data sources that have been defined by Windows using the odbc list command.
  4. Click DSN (data source name) listing provided by odbc list to query that DSN. odbc list will then list a default entry called “Excel Files” that you can use to choose any Excel (*.xls) file to load via ODBC. You must select an Excel file every time you issue an odbc command using this DSN. You can also define your own DSN that always points to a specific Excel file. On Windows, you would define this special DSN via the Control Panel called “Administrative Tools”, and then select “Data Sources (ODBC)”. More documentation is available from Microsoft concerning how to define your own Data Sources.
  5. Click the sheet/table corresponding to your data within the Excel file to describe the contents. You may need to issue the odbc query command with the dialog(complete) option if you selected an arbitrary Excel file in the previous list.
  6. If you are satisfied with the previous description of the sheet/table, you can click to load the described table.
  7. If all goes well, your data will load into Stata. There are, however, a few general reasons why loading Excel via ODBC may be problematic, and those are covered in section 5.

4. Copying a Stata graph into Excel or any other package

Once you have a suitable graph in Stata’s Graph window,

  1. Select Edit and click Copy Graph.
  2. Open or switch to Excel and move to where you want to paste the graph.
  3. Select Edit and click Paste.

These steps should also work in other packages that accept input in this manner.

5. Common problems

The following section is from material by Ted Anagnoson, California State Los Angeles; Dan Chandler, Trinidad, CA; Ronan Conroy, Royal College of Surgeons, Dublin; David Moore, Hartman Group; Paul Wicks, South Manchester University Hospitals Trust; Eric Wruck, Positive Economics; and Colin Fischbacher, University of Edinburgh.

The problems mentioned in it are primarily with respect to text-based methods of importing data from Excel to Stata, such as copying and pasting and import delimited. import excel handles most of these issues.

5.1 Nonnumeric characters

One cell containing a nonnumeric character, such as a letter, within a column of data is enough for Stata to make that variable a string variable. It is often easiest to fix this in Excel. Within Stata, suppose the problematic string variable is named foo. Here are three alternative ways to identify the rogue observations:

If appropriate, they can be replaced by missing, and then the variable as a whole can be converted to numeric by typing:

destring includes an option for stripping commas, dollar signs, percent signs, and other nonnumeric characters. It also allows automatic conversion of percentage data.

5.2 Spaces

What appear to be purely numeric data in Excel are often treated by Stata as string variables because they include spaces. People may inadvertently enter space characters in cells that are otherwise empty. Although Excel strips leading and trailing spaces from numeric entries, it does not trim spaces from character entries. One or more space characters by themselves constitute a valid character entry and are stored as such. Stata dutifully reads the entire column as a string variable.

Excel has a search and replace capability that enables you to delete these stray spaces, or you can use a text-processing program or a text editor on the text file. You can also use the solution in nonnumeric characters.

5.3 Cell formats

Much of the formatting in Excel interferes with Stata’s ability to interpret the data reasonably. Just before saving the data as a text file, make sure that all formatting is turned off, at least temporarily. You can do this by highlighting the entire spreadsheet, selecting Format, then selecting Cells, and clicking General.

However, no solution solves all problems. Here is a cautionary tale. A text file included address data. One column included house numbers, and a few were in the form 4/2. Excel decided these few were dates and converted them to 4th February. Setting all cells to a General format does not help because it converts these unwanted dates to 5 digit Excel date codes. One solution is to apply a Text format to the offending column when offered the option during Excel’s text import process. But even this works only if you have manageably few columns to look through and are aware of the possibility of the problem.

5.4 Variable names

Stata limits variable names to 32 characters and does not allow any characters that it uses as operators or delimiters. Also, variable names should start with a letter. People who are Excel users first and Stata users second are often creative with the names they apply to columns. Stata converts illegal column (field) names to labels and makes a best guess at a sensible variable name. Stata’s best guess, however, may not be as good as the name a user would choose knowing Stata’s naming restrictions.

For example, Stata will make variable names using the first 32 characters of the variable name and use the rest for a label. If the first 32 characters are not unique, subsequent occurrences will be called var1, var2, etc., or v1, v2, etc. (If you paste the data, the variable stub is var; if you use insheet, the stub is v, so be careful writing do-files.)

5.5 Missing rows and columns

Stata completely ignores empty rows in a spreadsheet but not completely empty columns. A completely empty column gets read in as a variable with missing values for every observation. Of course, no harm is done in either case, but spreadsheet users who wish to add blank columns and/or rows to enhance legibility may wish to note this difference.

It is best if the first row of data is complete with no missing data. If necessary, add a dummy row with every value present, and then once in Stata type

The missings command by Nicholas J. Cox, which allows variables or observations that are all missing to be easily dropped, was published in Stata Journal 15(4). Type search dm0085 for information on this command.

5.6 Leading zeros

With integer-like codes, such as ICD-9 codes or U.S. Social Security numbers, that do not contain a dash, leading zeros will get dropped when pasted into Stata from Excel. One solution is to flag the variable as a string in the first line: add a nonnumeric character in Excel on that line, and then remove it in Stata.

The missing leading zeros can also be replaced in a conversion to string with one Stata command line; for example,

The second argument on the right-hand side of this command is a format specifying leading zeros on conversion of nvar to its string equivalent. For more details on formats, see format.

5.7 Filename and folder

Confirm the filename and location of the file you are trying to read. Use Explorer or its equivalent to check.

Источник

Установите пакет XLS2DTA

ssc install xls2dta,replace

Результаты приведены ниже:

checking xls2dta consistency and verifying not already installed...
all files already exist and are up to date.

Установлен

Преобразовать файл XLSX в файл DTA

xls2dta:import excel no_miss.xlsx,first case(lower)

Первый случай здесь относится к первой строке Excel как имя переменной при преобразовании Excel в формат DTA.
результат:

(18 vars, 3,317 obs)
file d:academysharing_codedatano_miss.dta saved

Используйте файл DTA

use no_miss.dta

Введите данные просмотра и отредактируйте данные для дальнейшего анализа данных

I want to merge one using file (which is an Excel file) onto the masterfile in Stata. Might be easy but I don’t know how to save the Excel
file into a dta file so that I am, in turn, able to merge the two data sets in Stata.

I have read about the xls2dta command but I’m not sure if I’m looking in the right direction.

Nick Cox's user avatar

Nick Cox

35.1k6 gold badges31 silver badges47 bronze badges

asked Mar 9, 2022 at 20:57

Bella's user avatar

You do not need to convert the file with a special command like xls2dta. You just import it to Stata and save it in a temporary file in dta format and then you can merge that temporary file with your dta file.

Here is a reproducible example. All you need to do to run this code is to update the folder path in the local in the beginning of the code. You should be able to adapt the code in the «Solution» section to your code.

*Set this path to an example folder on your computer
local folder "C:Usersusernamemyfolder"

******************************************************************
*Prepare Excel example file
******************************************************************

*Use built in example data
sysuse auto, clear
*Rename all files but ID var make
foreach var of varlist _all {
    if "`var'"!="make" rename `var' `var'_ex
}
*save in excel format
export excel "`folder'/autoexcel.xls", firstrow(variables) replace

******************************************************************
*Solution
******************************************************************

*Use built in example data
sysuse auto, clear

*Load the excelfile into a temporary .dta file
preserve
    import excel "`folder'/autoexcel.xls", firstrow clear
    tempfile autoexcel_tmp
    save `autoexcel_tmp'
restore

*Merge the dta file in memory with tempfile of excel file in dta format
merge 1:1 make using `autoexcel_tmp'

answered Mar 9, 2022 at 21:53

TheIceBear's user avatar

TheIceBearTheIceBear

2,6129 silver badges23 bronze badges

Цитата:

Сообщение от Borland
Посмотреть сообщение

lesha1974
Строго говоря, прежде чем что-то куда-то конвертировать — нужно, как минимум, иметь представление о предмете конвертации.
Откуда взялся файл, какая программа для него «родная» и т.п.
Если, к примеру, этот файл сформирован неким электронно-измерительным прибором — в документации к прибору должно быть указание на программу для работы с ним (и, обычно, сама программа идёт в комплекте поставки).
Задача же конвертации «файла вообще» в общем случае неразрешима…

Какая-то программа работы с со статистикой.

Родная, судя по всему, к таким («dta») файлам — это программа stata. Хотя, это условно: похоже, и другие программы с этим расширением работают как с родным.
Я бы тоже хотел получше узнать что за файл, но, судя по тому, что откуда я его скачал — было много благодарностей за файл и никто не спросил (кроме меня в самом конце) что это за фал — это какой-то стандартный, в каких-то «статистических кругах» формат.
В сети пишут, что с форматом работает программа stata так, что склоняюсь к выводу, что изначально он для этой программы и был создан. Но в свободном доступе в сети найти её не смог.

добавлено через 4 минуты

Цитата:

Сообщение от Merlin Cori
Посмотреть сообщение

а откуда взялся этот файл .dta? и из чего следует, что его надо открывать с помощью

Ну это же кто-то в выложил по ссылке, чтото выше привёл (https://www.researchgate.net/post/Co…if_you_have_it). Он сам этот файл создал – скомпилировал из каких-то данных. Это – какой-то статистический формат данных типа экселя.
В сети пишут, что с ним работает программа Stata (выше же некоторые ссылки тоже приводил).

Понравилась статья? Поделить с друзьями:
  • From excel to drupal
  • Frequency word and phrase
  • From excel to dbf
  • From excel to databases with python
  • From excel to csv конвертер