根据另一列中的4个值创建新列 [英] Create new column based on 4 values in another column
问题描述
我想根据另一列中的4个值创建一个新列。
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.
我如何在R中做到这一点?
我需要有人帮忙解决这个问题。我试过if / else和ifelse,但似乎没有工作。谢谢
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
推荐答案
您有一个特殊情况,即查找索引为整数1:4的值。这意味着您可以使用向量索引在一个简单的步骤中解决您的问题。
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:
set.seed(1)
dat <- data.frame(col1 = sample(1:4, 10, replace = TRUE))
接下来,定义查找值,并使用 [
子集查找期望的结果:
Next, define the lookup values, and use [
subsetting to find the desired results:
values <- c("G", "H", "J", "K")
dat$col2 <- values[dat$col1]
结果:
dat
col1 col2
1 2 H
2 2 H
3 3 J
4 4 K
5 1 G
6 4 K
7 4 K
8 3 J
9 3 J
10 1 G
更一般地说,你可以使用 [
子集与匹配
以解决此类问题:
More generally, you can use [
subsetting combined with match
to solve this kind of problem:
index <- c(1, 2, 3, 4)
values <- c("G", "H", "J", "K")
dat$col2 <- values[match(dat$col1, index)]
dat
col1 col2
1 2 H
2 2 H
3 3 J
4 4 K
5 1 G
6 4 K
7 4 K
8 3 J
9 3 J
10 1 G
这篇关于根据另一列中的4个值创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!