paco.pacheco
paco.pacheco

Reputation: 83

R and ifelse function

I'm stuck in a simple problem argument with the ifelse function in R. I'm a new user of R and I'm trying to fill blanks in a column ("first column") depending on values in another column ("second column").

As I try ifelse function, I'm getting this error "argument "no" is missing, with no default"

All I need is: if the test (condition) is FALSE, keep the values (from a factor variable) in the "first column" as they are.

This is an example of my data frame which has ~6000 obs

# 
#       first                                   second third
# 1 Cluster 1                               Chest Pain     1
# 2                           Coronary Artery Diseases     1
# 3 Cluster 6                                   Anemia     5
# 4 Cluster 7 Hypertension and Cerebrovascular Disease     4
# 5              Chronic Obstructive Pulmonary Disease     2
# 6 Cluster 5                                 Diabetes    10

My try is

sample$first= ifelse(sample$second=="Coronary Artery Diseases","Cluster 10",sample$first)

The result of this is filling "Cluster 10" in first column if a have "Coronary Artery Diseases" in the second column BUT all the remaining obs in the first column I get a number. The problem is that "first" is a factor variable and I need it to be a factor.

Any suggestions?

data

sample <- structure(list(first = c("Cluster 1", "", "Cluster 6", "Cluster 7", 
"", "Cluster 5"), second = c("Chest Pain", "Coronary Artery Diseases", 
"Anemia", "Hypertension and Cerebrovascular Disease", 
"Chronic Obstructive Pulmonary Disease", "Diabetes"), 
third = c("1", "1", "5", "4", "2", "10")), 
.Names = c("first", "second","third"), 
class = "data.frame", row.names = c(NA, -6L))

Upvotes: 2

Views: 1717

Answers (1)

paco.pacheco
paco.pacheco

Reputation: 83

As the first column was a factor (not shown in data above), when using ifelse to replace values, it coerced the other values in the column to the factor levels (removing their labels). This could be worked around by using as.character()

sample$first <-  as.factor(ifelse(sample$second=="Coronary Artery Diseases",
                                   "Cluster 10",as.character(sample$first))

Upvotes: 3

Related Questions