如何在R中将一个变量分成两个变量?
我有一个变量 x ,它可以取五个值(0,1,2,3,4)。我想将变量分为两个变量。变量 1 应该包含值 0,变量 2 应该包含值 1、2、3 和 4。 我确信这很容易,但我不知道我需要做什么。
我的数据是什么样的:
|variable x|
|-----------|
|0|
|1|
|0|
|4|
|3|
|0|
|0|
|2|
所以我得到了表:
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
125 | 34 | 14 | 15 | 15 |
但我希望我的数据看起来像这个
变量 1 |
---|
125 |
变量 2 |
---|
78 |
所以变量 1 应该包含 0 在我的数据中出现的频率数据
和变量 2 应该包含我的数据中 1、2、3 和 4 出现频率的总和
I have a variable x which can take five values (0,1,2,3,4). I want to divide the variable into two variables. Variable 1 is supposed to contain the value 0 and variable two is supposed to contain the values 1,2,3 and 4.
I'm sure this is easy but I can't find out what i need to do.
what my data looks like:
|variable x|
|-----------|
|0|
|1|
|0|
|4|
|3|
|0|
|0|
|2|
so i get the table:
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
125 | 34 | 14 | 15 | 15 |
But I want my data to look like this
variable 1 |
---|
125 |
variable 2 |
---|
78 |
So variable 1 is supposed to contain how often 0 is in my data
and variable 2 is supposed to contain the sum of how often 1,2,3 and 4 are in my data
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过测试
x == 0
是否需要确切的标题来将变量转换为逻辑,请执行:
如果要将变量更改为可以执行的因素:
>由
You can convert the variable to logical by testing whether
x == 0
If you want the exact headings, you can do:
And if you want to change the variable to a factor you could do:
Created on 2022-04-02 by the reprex package (v2.0.1)
基本 R
您可以使用
cbind
:tidyverse
base R
You can use
cbind
:tidyverse
从向量开始,我们可以从
table
中获取频率,然后将其放入数据帧中。然后,我们可以创建一个名称折叠的新列(即1,2,3,4
),并获取除第一列之外的所有列的行总和。输出
然后,要在 2 个数据框中创建 2 个变量,您可以将列拆分为列表,更改名称,然后放入全局环境中。
或者你可以直接子集:
Beginning with the vector, we can get the frequency from
table
then put it into a dataframe. Then, we can create a new column with the names collapsed (i.e.,1,2,3,4
) and get the row sum for all columns except the first one.Output
Then, to create the 2 variables in 2 dataframes, you can split the columns into a list, change the names, then put into the global environment.
Or you could just subset:
更新:删除第一个答案:
数据:
Update: deleted first answer:
data: