Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Replacing missing values

    My data is scattered over several columns. I want to shift the non-missing values from the nearest right side columns to the corresponding rows of left side columns. I have been doing this with simple replace commands or using concat command:

    egen B_new = concat(C D E F G)
    replace B = B_new if B == ""
    drop B_new
    drop C D E F G

    However, I have such problem in all columns and I need to shift the values to the left side columns till there is no missing values. I have many such files to work on, please help with a loop. The variables name are A,B,C,D,E,F......so on

    Click image for larger version

Name:	Screenshot 2023-11-24 123254.png
Views:	2
Size:	30.8 KB
ID:	1735025
    Attached Files

  • #2
    Try this:
    Code:
    ds A, not
    local columns `r(varlist)'
    rename (`columns') address=
    gen `c(obs_t)' obs_no = _n
    reshape long address, i(obs_no) j(column) string
    drop if missing(address) | address == "Address"
    by obs_no (column), sort: gen column2 = _n
    drop column
    reshape wide address, i(obs_no) j(column2)
    Please read the Forum FAQ for excellent advice on how to show data (specifically in #12). You will learn there, among other things, that screenshots are not nearly as helpful as you might think they are. In particular, it is not possible to import a screenshot into Stata. Consequently this code is untested and may contain errors. If it does not work, please post back posting in the helpful way example data that demonstrates how the code is not producing the intended results, that is, with the -dataex- command.

    If you are running version 18, 17, 16 or a fully updated version 15.1 or 14.2, -dataex- is already part of your official Stata installation. If not, run -ssc install dataex- to get it. Either way, run -help dataex- to read the simple instructions for using it. -dataex- will save you time; it is easier and quicker than typing out tables. It includes complete information about aspects of the data that are often critical to answering your question but cannot be seen from tabular displays or screenshots. It also makes it possible for those who want to help you to create a faithful representation of your example to try out their code, which in turn makes it more likely that their answer will actually work in your data.

    Added: Note that no loop is required.

    Comment

    Working...
    X