r - How to reclassify dataframe column? -


i working on reclassifying values in 1 dataframe column , adding values column. following script attempts apply reclassification function column , output values column in dataframe.

a = c(1,2,3,4,5,6,7)  x = data.frame(a)  # reclassify values in x$a reclass = function(x){   # 1 - spruce/fir          = 1   # 2 - lodgepole pine      = 1   # 3 - ponderosa pine      = 1   # 4 - cottonwood/willow   = 0   # 5 - aspen               = 0   # 6 - douglas-fir         = 1   # 7 - krummholz           = 1   if(x == 1) return(1)   if(x == 2) return(1)   if(x == 3) return(1)   if(x == 4) return(0)   if(x == 5) return(0)   if(x == 6) return(1)   if(x == 7) return(1) }  # add new column x$b = 0  # apply function on new column b = lapply(x$b, reclass(x$a)) 

the error message:

> b = lapply(x$b, reclass(x$a)) error in match.fun(fun) :    'reclass(x$a)' not function, character or symbol in addition: warning message: in if (x == 1) return(1) :   condition has length > 1 , first element used 

the intended output should following

a = c(1,2,3,4,5,6,7) b = c(1,1,1,0,0,1,1) x = data.frame(a, b) 

i have read seemingly similar question (reclassify select columns in data table), although appears addressing changing actual class (e.g. numeric) of column.

how can take values 1 column in dataframe, apply reclassification function, , output values new column?

here, i'd (something like):

conifertypes <- c(1,2,3,6,7) x$b <- as.integer(x$a %in% conifertypes) x #   b # 1 1 1 # 2 2 1 # 3 3 1 # 4 4 0 # 5 5 0 # 6 6 1 # 7 7 1 

Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -