我有一个看起来像这样的数据框:
cnt bnk qst ans
1 Country 1 Bank 1 q1 1
2 Country 2 Bank 2 q1 1
3 Country 3 Bank 3 q1 3
4 Country 4 Bank 4 q1 1
5 Country 1 Bank 1 q2 1
6 Country 2 Bank 2 q2 2
7 Country 3 Bank 3 q2 3
8 Country 4 Bank 4 q2 4
9 Country 1 Bank 1 q3 1
10 Country 2 Bank 2 q3 1
11 Country 3 Bank 3 q3 2
12 Country 4 Bank 4 q3 1
供您参考,q
' 代表“问题”。所以,q2
是“问题2”。同样,ans
是响应。
现在,我想根据中的响应创建一个分类变量q2
。特别是我想分配以下类别:
- 上市
- 私人的
- 混合
- 其他
所以,如果ans=1
to qst=q2
,这是“Public”,如果ans=2
toqst=q2
这是“Private”等。所以,我之后的数据框应该是这样的:
cnt bnk qst ans dummy
1 Country 1 Bank 1 q1 1 Public
2 Country 2 Bank 2 q1 1 Private
3 Country 3 Bank 3 q1 3 Mixed
4 Country 4 Bank 4 q1 1 Other'
5 Country 1 Bank 1 q2 1 Public
6 Country 2 Bank 2 q2 2 Private
7 Country 3 Bank 3 q2 3 Mixed
8 Country 4 Bank 4 q2 4 Other'
9 Country 1 Bank 1 q3 1 Public
10 Country 2 Bank 2 q3 1 Private
11 Country 3 Bank 3 q3 2 Mixed
12 Country 4 Bank 4 q3 1 Other'
我试图使用 ifelse,但我没有做我想做的事。有人可以给我一些建议吗?
数据
dput(df)
structure(list(cnt = c("Country 1", "Country 2", "Country 3",
"Country 4", "Country 1", "Country 2", "Country 3", "Country 4",
"Country 1", "Country 2", "Country 3", "Country 4"), bnk = c("Bank 1",
"Bank 2", "Bank 3", "Bank 4", "Bank 1", "Bank 2", "Bank 3", "Bank 4",
"Bank 1", "Bank 2", "Bank 3", "Bank 4"), qst = structure(c(1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L), .Label = c("q1",
"q2", "q3"), class = "factor"), ans = c(1L, 1L, 3L, 1L, 1L, 2L,
3L, 4L, 1L, 1L, 2L, 1L), dummy = c(NA, NA, NA, NA, "Public",
"Private", "Mixed", "Other", NA, NA, NA, NA)), .Names = c("cnt",
"bnk", "qst", "ans", "dummy"), row.names = c("1", "2", "3", "4",
"5", "6", "7", "8", "9", "10", "11", "12"), class = "data.frame")