adding a column in R to a dataframe [duplicate]

假如想象 提交于 2019-12-13 08:29:41

问题


How do I add a column to a dataframe in R based on values in another column of a dataframe ?

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]


回答1:


Using cut:

within(x, category <- as.integer(cut(n,c(-Inf,2,4,Inf)))-1)

Using 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))



回答2:


If you have:

x = data.frame(n = 1:6)

and only have three categories, then the easiest solution would be:

x$category = 0
x$category[x$n > 2] = 1
x$category[x$n > 4] = 2

If you want to be really clever, then you could do:

x$category = floor(x$n/2.5)

The floor function` just rounds down.



来源:https://stackoverflow.com/questions/18684964/adding-a-column-in-r-to-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!