简体   繁体   English

通过将R中数据框的现有列中的值分组来创建新列

[英]create a new column by grouping values from an existing column of a dataframe in R

I have the following dataframe: 我有以下数据框:

  Date       power                
1 16/12/2006 4.216              
2 17/12/2006 5.360              
3 18/12/2006 5.374              
4 19/12/2006 5.388                 
5 20/12/2006 3.666                 
6 21/12/2006 3.520    

I would like to create a new column to group the values of power into intervals say 0-0.5, 0.5-1 and so on upto 5.5-6. 我想创建一个新列,将功率值分组为间隔,例如0-0.5、0.5-1,以此类推,直到5.5-6。 I'm fairly new to R. I think it is possible using split function but not sure how to do that. 我对R相当陌生。我认为可以使用split函数,但不确定如何做到这一点。 Thanks in advance. 提前致谢。

First you would need to create your bins. 首先,您需要创建垃圾箱。

# Create break from  0 to 10 in 0.5 intervals
breaks = seq(0, 10, 0.5)

# Create bin column
data$bins = cut(data$power, breaks)

You can keep the value of data$bins as intervals, or convert (coerce) to numeric by 您可以将data $ bins的值保留为间隔,也可以通过以下方式将(强制)转换为数字:

 data$bins = as.numeric(data$bins).

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM