简体   繁体   中英

Transform all factor columns to their type (char, numeric)?

I have a data frame (df) with some factorized columns say:

col1 (numeric factor) col2 (char factor) col3 (ord factor p < r < c)
1                     a                  r 
2                     b                  p
3                     c                  c

Where 1,2,3 are numeric factors, a,b,c are char factors and col3 p,r,c are ord factor column.

Please advise how can I transform all of them in few lines to numbers and chars to make col1 of type numeric, col2 and col3 of type char. And please help me how can I locate ord factor variables in dataframe?

Thanks.

We could do this by looping through the columns, convert to character and then use type.convert

df1[] <- lapply(df1, function(x) type.convert(as.character(x), as.is = TRUE))

data

df1 <- data.frame(col1 = c('1', '2', '3'), col2 = c('a', 'b', 'c'),
             col3 = ordered(c('p', 'r', 'c')))

用反复试验挖掘一些知识,我认为这是一个不错的解决方案:名称(x [sapply(x,is.ordered)])专家们怎么看?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM