R: Conditional Replacement of values in several columns in data frame -


i have read several posts on applied changing 1 column/variable. need replace values in number of columns in dataframe @ once. thought should work it's not , cannot figure out why.

positive <- c("yes", "science") temp1 <- c("yes", "no","","science", "only-child") temp2 <- c("yes", "no",""," yay people!", "pessimist") temp3 <- cbind(temp1,temp2) colnames(temp3) <- c("feature1","feature2") temp <- as.data.frame(temp3) 

this not work:

for (i in temp) {   ifelse(i %in% positive, 1, i) } 

however, doing on 1 column works:

test <- ifelse(temp$feature1 %in% positive, 1, temp$feature1) test 

so suspect not want check results in expected:

for (i in temp) {   print(i %in% positive) } 

the output should this:

  feature1     feature2          1            1         no           no           1  yay people! only-child    pessimist 

so missing?

the first thing that's causing problems in example conversion of strings factors. assuming that's fixed, here's way appropriate indices , assign 1 them:

temp <- as.data.frame(temp3, stringsasfactors=false) temp[apply(temp, 2, function(x) x %in% positive)] <- 1 

Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -