在R中将列添加到数据帧 [英] adding a column in R to a dataframe
本文介绍了在R中将列添加到数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何根据数据框架的另一列中的值向R中的数据框添加列?
How do I add a column to a dataframe in R based on values in another column of a dataframe ?
例如,如果我有一列为x $ n = [1,2,3,4,5,6](其他列中的值不重要,我想要另一列作为类别列,如果x $ n <2,则分配值0,如果x $如果x $ n> 4,则n在3到4之间,3,因此我的相应列将为x $ category = [0,0,1,1,2,2]
For eg if I have one column as x$n = [1,2,3,4,5,6] (values in other colums dont exactly matter. And I want another column as a 'category' column that assigns value 0 if x$n < 2, 1 if x$n is between 3 and 4 and 3 if x$n > 4. So that my corresponding column would be x$category = [0,0,1,1,2,2]
推荐答案
使用 cut
:
within(x, category <- as.integer(cut(n,c(-Inf,2,4,Inf)))-1)
使用 ifelse
:
within(x, category <- ifelse(n>4, 2, ifelse(n>2, 1, 0)))
使用隐式布尔 - >整数强制::
Using implicit boolean -> integer coercion::
within(x, category <- (n>2) + (n>4))
这篇关于在R中将列添加到数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文