Announcement

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

  • Drop variables based on name

    Hi, I have a dataset with 100 variables, 50 of which are called Xi_ante and 50 of which are called Xi_post.

    I want to delete those with "_post" from my dataset.

    I tried using the following command:
    Code:
    global variables [all variables Xi without _ante or _post]
    
    foreach `var' of global variables{
    drop `var'_post
    }
    But I get a syntax error. Is there any way to tell stata to drop the variables that contain "_post" in their name?

    Thank you!


  • #2
    Code:
    drop *_post

    Comment


    • #3
      easier than I thought... thanks a lot! I was wondering though, how come that command didn't work? I was going to use a similar loop to rename variables
      Last edited by Joan Marti; 30 Nov 2021, 09:33.

      Comment


      • #4
        Originally posted by Joan Marti View Post
        easier than I thought... thanks a lot! I was wondering though, how come that command didn't work? I was going to use a similar loop to rename variables
        Code:
        foreach var of global variables{
            drop `var'_post
        }
        Actually, you may use -rename group- instead of a loop to rename variable names.
        Last edited by Fei Wang; 30 Nov 2021, 09:46.

        Comment


        • #5
          Joan:
          -split- might be another option:
          Code:
          . set obs 100
          number of observations (_N) was 0, now 100
          
          . g wanted="Xi_ante" in 1/50
          
          . replace wanted="Xi_post" in 51/100
          
          . split wanted, p(_post)
          
          . drop if wanted1=="Xi"
          
          . drop wanted
          
          . rename wanted1 wanted
          
          .
          Kind regards,
          Carlo
          (Stata 19.0)

          Comment


          • #6
            Very useful suggestions, thank you!!

            Comment

            Working...
            X