根据R中的条件创建新的列变量 [英] Create new column variables based upon condition in R
问题描述
我不知道为什么这不起作用。我尝试了各种各样的方式,它只是不起作用。并不是因为我自己使用if语句而得到错误,但它并不适用。
I don't know why this is not working. I have tried it various ways and it just does not work. It's not that I get an error using the if-statements I made myself, but it doesn't apply right.
基本上,有一列数据$年龄
和列数据$ Age2
。
如果数据$年龄
的值是50 - 100,我希望 Data $ Age2
为该特定行说50 - 100年。
If Data$Age
is value 50 - 100, I want Data$Age2
to say "50-100 Years" for that particular row.
同样,如果 Data $ Age
是25-50,我想 Data $ Age2
对其适用的行说25-50岁。
Likewise, if Data$Age
is 25-50, I want Data$Age2
to say "25-50 Years" for the rows to which it applies.
在R中这样做最干净的方法是什么? ?
What would the cleanest way to go about doing this in R?
推荐答案
dplyr可能有最清晰的解决方案
dplyr may have the cleanest solution to this
使用Len Greski的样本数据如下......
Using Len Greski's sample data below...
data <- data.frame(Age1 = round(runif(100)*100,0))
data%>%
mutate(Age2 = ifelse(between(Age1, 25, 50), "25 - 50 Years",
ifelse(between(Age1, 51, 100),"51 - 100 Years", "Less than 25 years old")))
假设您只想要列的两个值。 ifelse()
对两个以上的比赛效率不高,比如说100。如果不是,我将不得不考虑另一种方法。
Assuming you only want two values for the column. ifelse()
is not efficient for more than two matches, say 100, though. I'll have to think of an alternative approach in the event that its not.
编辑:
或Len建议在这个评论中。
or as Len has suggested below this, in a comment.
data%>%
mutate(Age2 = cut(Age1,c(24,50,100),c("25-50 years","51-100 Years")))
这篇关于根据R中的条件创建新的列变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!