Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

r - Adding new column with conditional values using ifelse

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This will help you out -

# Creating a data frame 

M <- data.frame(c("A","B","C"),c(5,100,60))

names(M) <- c("Letter","Number")

#adding a column 


# 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

# M$Size[M$Number <= 50] <- "Small"
# Edit: No need to subset "Small"
M$Size <- "Small"
M$Size[M$Number >50 & M$Number<70] <- "Medium"
M$Size[M$Number > 70] <- "Big"

#      Letter Number   Size
# 1      A      5      Small
# 2      B    100      Big
# 3      C     60      Medium

See this on R-Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...