如何根据R编程中的条件将列添加到数据帧中 [英] How to add column into a dataframe based on condition in R programming

查看:129
本文介绍了如何根据R编程中的条件将列添加到数据帧中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下数据框。
我想做的是在该数据框中添加另一列(第7列)。
如果Sepal.Length> = 5分配UP,则条件为否则分配DOWN
我们称该栏为规则。

 >虹膜
萼片长度萼片宽度花瓣长度花瓣种类
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
7 4.6 3.4 1.4 0.3 setosa
8 5.0 3.4 1.5 0.2 setosa
9 4.4 2.9 1.4 0.2 setosa
10 4.9 3.1 1.5 0.1 setosa
...

在R中做什么?

解决方案

尝试

  iris $ Regulation< ;  -  ifelse(iris $ Sepal.Length> = 5,UP,DOWN)


For example I have the following data frame. What I want to do is to add another column (7th column) in to that data frame. The condition is if Sepal.Length >=5 assign "UP" else assign "DOWN". We'd call that column "Regulation".

 > iris 
     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
    1            5.1         3.5          1.4         0.2     setosa
    2            4.9         3.0          1.4         0.2     setosa
    3            4.7         3.2          1.3         0.2     setosa
    4            4.6         3.1          1.5         0.2     setosa
    5            5.0         3.6          1.4         0.2     setosa
    6            5.4         3.9          1.7         0.4     setosa
    7            4.6         3.4          1.4         0.3     setosa
    8            5.0         3.4          1.5         0.2     setosa
    9            4.4         2.9          1.4         0.2     setosa
    10           4.9         3.1          1.5         0.1     setosa
    ...

What's the way to do that in R?

解决方案

Try

iris$Regulation <- ifelse(iris$Sepal.Length >=5, "UP", "DOWN")

这篇关于如何根据R编程中的条件将列添加到数据帧中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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