根据另一列中的 4 个值创建新列
我想根据另一列中的 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
更一般的,你可以使用[
子集结合match
来解决这类问题:
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