[英]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.