如何根据条件在data.frame中创建新变量? [英] How to create a new variable in a data.frame based on a condition?

查看:195
本文介绍了如何根据条件在data.frame中创建新变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个数据框

x   y
1   1
2   4 
4   5 

如何将新变量添加到数据帧,使得如果x小于或等于1,如果x在3到5之间,则返回好;否则,返回差。

how can you add a new variable to the dataframe such that if x is less than or equal to 1 it returns "good" if x is between 3 and 5 it returns "bad" else returns "fair"

x   y  w
1   1  "good"
2   2   "fair"
5   5   "bad"

应用了ocram。所示的方法,但是此方法在这里不起作用。

Applied the method shown by ocram., however this one here does not work.

d1 <- c("e", "c", "a")
d2 <- c("e", "a", "b")

w <- ifelse(d1 == "e" & (d2=="e"), 1, ifelse((d1 == "a") & (d2 =="b"), 2, ifelse(d1 == "e"),3,99))

有什么想法吗?
谢谢

Any ideas? Thanks

推荐答案

一个显而易见的简单方法是使用 if-else条件。在该示例中

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

**对于其他问题在编辑**
中,这是您期望的吗?

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

如果您对 ifelse 函数不满意,也可以使用 if else 此类应用程序的语句。

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

这篇关于如何根据条件在data.frame中创建新变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆