简体   繁体   English

如何在R中基于数值条件添加具有值的新列?

[英]How to add a new column with values based on numeric value condition in R?

I have a data frame with a colmn called concentration with numeric values. 我有一个数据框,它带有一个称为浓度的带有数值的列。

Concentration
700657  
850789  
900123  
1011234  
750001

I want to add a new column CDrange that has values 700k+,800k+,900k+,1000k+. 我想添加一个新列CDrange,其值是700k +,800k +,900k +,1000k +。 The values in the new column will be assigned based on the value of concentration, eg if value is 700657, the calculated value should be 700k+, if value is 850789 then value as 800k+ and so on. 新列中的值将基于浓度值进行分配,例如,如果值是700657,则计算值应为700k +,如果值是850789,则值应为800k +,依此类推。 How do I write a function without using if else loops. 如何在不使用if循环的情况下编写函数。 The new column should look like 新列应如下所示

Concentration       CDrange          
700657              700k+ 
850789              800k+ 
900123              900k+ 
1011234             1000k+ 
750001              700k+

Please provide on some suggestions on how to proceed. 请提供一些有关如何进行的建议。 I have tried using subset function but I am unable to keep the dataframe together. 我尝试使用子集函数,但无法将数据框保持在一起。

See ?cut and ?findInterval . 参见?cut?findInterval

df$CDrange <- cut(df$Concentration, c(700000, 800000, 900000, 1000000, Inf),
                  labels=c("700k+","800k+","900k+","1000k+") right=FALSE)

Check this example: 检查以下示例:

x <- c(800000, 800001, 800999, 1234567)
paste0(x %/% 1000, ifelse((x %% 1000)>0, "k+", "k"))

#[1] "800k"   "800k+"  "800k+"  "1234k+"

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

相关问题 根据R中的数值条件创建一个新的字符值列。 - Creating a new column of character values based on numeric value condition in R? 如何在 r 中按组查找基于条件的值之间的差异并使用该值创建新列? - How to find difference between values based on condition by group in r and create new column with that value? 根据 R 中的字符串值添加新列 - Add a new column based on string values in R R - 如何根据另一列中值相等的条件为新列选择值 - R - How to choose values for new column based on condition that values are equal in another column 根据另一列的条件在 R 中添加新列 - add new column in R based on condition from another column 如何根据R中的条件替换列值 - How to replace column values based on a condition in R 根据 R 中存在的值添加新列 - Add a new column based on the presence of a value in in R 如何使用R中的if和non-if函数基于另一列中的条件在新列中分配值 - How to assign values in new column based on condition in another column using if and non-if functions in R 如何使用apply()根据R中不同列中的条件添加新列 - How to use apply() to add a new column based on a condition in a diiferent column in R R添加一个新列并根据多个条件使用字符串值填充它 - R adding a new column and populating it with string values based on multiple condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM