Hello Statalisters,
thank you in advance for considering the following.
I'm trying to creating new variables names from a single variables value, and to assign these variables values taken from another variable.
My data appears as the following:
id count class
1 1 c1
1 2 c2
1 3 c3
2 11 c1
2 22 c2
2 33 c3
I want class too form names of new variables, where each of these variables assume the value of the associated count. More specifically, i want the transformation to result in the following:
id c1 c2 c3
1 1 2 3
2 11 22 33
I've seen some previous posts (e.g., https://www.statalist.org/forums/for...o-one-stacking) but I don't seem to be able to apply these to my data
My code is as follows:
input id count str5 class
1 1 c1
1 2 c2
1 3 c3
2 11 c1
2 22 c2
2 33 c3
end
levelsof class, local(ccc)
foreach newclass in `ccc' {
gen `newclass' = count if class == "`newclass'"
rename `newclass' ccc`newclass'
}
list
----
My output:
+--------------------------------------------+
| id count class cccc1 cccc2 cccc3 |
|--------------------------------------------|
1. | 1 1 c1 1 . . |
2. | 1 2 c2 . 2 . |
3. | 1 3 c3 . . 3 |
4. | 2 11 c1 11 . . |
5. | 2 22 c2 . 22 . |
|--------------------------------------------|
6. | 2 33 c3 . . 33 |
+--------------------------------------------+
I can probably transform through other steps using Collapse or Sum for my example data. However, the number of classes in my actual data is quite large, making use of these somewhat difficult.
Does anyone have suggestions on how to convert my data to
id c1 c2 c3
1 1 2 3
2 11 22 33
?
thanks again,
Ed
0 Response to create variable names from a variable value, and then group by id
Post a Comment