Announcement

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

  • Using Levelsof return to rename Column

    Dear all,

    Im trying to rename column based on levelsof return function :
    I tried
    Code:
    levelsof varName if exp
    it returns “‘myValue’” and then I want to achieve this
    Code:
    rename col1 _this returned value_
    its not working, I guess because it returns kind of a string value ? Has anyone any idea how to achieve that.

    Regards,
    Kevin

  • #2
    I'm not sure I follow what you want to do, but it sounds like it might be this:

    Code:
    levelsof varName if exp, local(returned_values)
    local new_var_name: word 1 of `returned_values'
    rename col1 `new_var_name'
    There are a few cautions about this. First, if exp != 0 does not define a unique observation in your data set, then -levelsof- will return several different values. The above code assumes you intend to use the first of those. But you need to think through how you actually want to handle that situation. Another problem is that varName, unless it is actually populated with names of variables, might contain something that is not a legal variable name in Stata, and if that happens, the -rename- command will, of course, fail. So if you encounter that problem, then what you want to do is not possible at all. You can, however, come close by doing it this way:

    Code:
    levelsof varName if exp, local(returned_values)
    local new_var_name: word 1 of `returned_values'
    local new_var_name = strtoname(`"`new_var_name'"')
    rename col1 `new_var_name'
    The -strtoname()- function takes a string argument and returns the same string with all characters that are illegal in a Stata variable name replaced by underscore (_) characters.

    Comment

    Working...
    X