I have a data frame with more than 400.000 observations and I'm trying to add a column to it which its values depend on another column and sometimes multiple ones.
Here is a simpler example of what I'm trying to do :
# Creating a data frame
M <- data.frame(c("A","B","C"),c(5,100,60))
names(M) <- c("Letter","Number")
#adding a column
M$Size <- NA
# if Number <= 50 Size is small,
# if Number is between 50 and 70, Size is Medium
# if Number is Bigger than 70, Size is Big
ifelse (M$Number <=50, M$Size <-"Small",
ifelse(M$Number <= 70,
M$Size <- "Medium",
M$Size <- "Big"
))
When I run the Code, the output I get is :
[1] "Small" "Big" "Medium"
But the "Size" column in M is always the last condition in the ifelse function :
> print (M)
Letter Number Size
1 A 5 Big
2 B 100 Big
3 C 60 Big
The Result that I want :
> print (M)
Letter Number Size
1 A 5 Small
2 B 100 Big
3 C 60 Medium
I can solve the problem by subsetting each conditionsubset
and using rbind
to get the result I want but the code will be very long and since the original data frame I'm working on is big, it'll take more time to run. So I'm wondering how can I fix this issue ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…