JodeCharger100
JodeCharger100

Reputation: 1059

How to split a string in one variable to create two variables?

Suppose I have a list of names under variable Names:

Beckham, Benjamin  
Roy, Andrew R. 
Shaunson, David T.

How do I create two variables, one named Last_name, the other First_name?

Variable Last_name will be a list containing:

Beckham
Roy
Shaunson

Variable First_name will be a list containing:

Benjamin
Andrew R.
David T.

Upvotes: 1

Views: 5763

Answers (2)

JodeCharger100
JodeCharger100

Reputation: 1059

I worked on it, and found an alternate solution:

generate inbet = strpos(Names, ",")
generate str1 Last_name = "" 
replace Last_name = substr(inbet,1,inbet - 1)
generate str1 First_name = "" 
replace First_name = substr(Name,inbet + 1,.)

Upvotes: 1

Nick Cox
Nick Cox

Reputation: 37183

Your understanding of what you want should lead you to look for a Stata command named (something like) split. Seek (with e.g. search) and you will find.

clear 
input str42 whatever 
"Beckham, Benjamin" 
"Roy, Andrew R."
"Shaunson, David T."
end 

split whatever, parse(,) 
rename (whatever?) (lastname firstname) 

list 

     +--------------------------------------------+
     |           whatever   lastname    firstname |
     |--------------------------------------------|
  1. |  Beckham, Benjamin    Beckham     Benjamin |
  2. |     Roy, Andrew R.        Roy    Andrew R. |
  3. | Shaunson, David T.   Shaunson     David T. |
     +--------------------------------------------+

Upvotes: 1

Related Questions