根据另一列中的 4 个值创建新列
我想根据另一列中的 4 个值创建一个新列。
if col1=1 then col2= G;
if col1=2 then col2=H;
if col1=3 then col2=J;
if col1=4 then col2=K.
我如何在 R 中执行此操作? 请我需要有人帮助解决这个问题。我尝试过 if/else 和 ifelse 但似乎都不起作用。谢谢
I want to create a new column based on 4 values in another column.
if col1=1 then col2= G;
if col1=2 then col2=H;
if col1=3 then col2=J;
if col1=4 then col2=K.
HOW DO I DO THIS IN R?
Please I need someone to help address this. I have tried if/else and ifelse but none seems to be working. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用嵌套的
ifelse
:在这个简单的情况下,它是多余的,但对于更复杂的情况......
You could use nested
ifelse
:In this simple case it's overkill, but for more complicated ones...
您有一个特殊情况,即查找索引为整数 1:4 的值。这意味着您可以使用向量索引轻松地解决您的问题。
首先,创建一些示例数据:
接下来,定义查找值,并使用
[
子集化来查找所需的结果:结果:
更一般地,您可以使用
[
子集化组合用match
来解决此类问题:You have a special case of looking up values where the index are integer numbers 1:4. This means you can use vector indexing to solve your problem in one easy step.
First, create some sample data:
Next, define the lookup values, and use
[
subsetting to find the desired results:The results:
More generally, you can use
[
subsetting combined withmatch
to solve this kind of problem:有多种方法可以做到这一点,但这里是一种。
这是使用
car
的recode
的一个。此问题的另一个问题:
There are a number of ways of doing this, but here's one.
Here's one using
car
'srecode
.One more from this question:
您可以查看
?symnum
。就你而言,类似:
应该让你接近。
You could have a look at
?symnum
.In your case, something like:
should get you close.