Converting columns to character with sapply

蹲街弑〆低调 提交于 2020-01-07 08:25:11

问题


I have a dataframe test whose columns are factors

class(test)
[1] "data.frame"

sapply(test, class)
  street     city    state 
"factor" "factor" "factor" 

If I try to convert these columns to character with sapply() , something goes wrong and I not sure why

test <- as.data.frame(sapply(test, as.character))

sapply(test, class)
  street     city    state 
"factor" "factor" "factor" 

I would expect the output to be all character columns. Why are the columns not converting and how would one convert all factor columns to character?

Here is the test data:

> dput(test)
structure(list(street = structure(c(5L, 1L, 6L, 2L, 3L, 4L), .Label = c("12057 Wilshire Blvd", 
"15300 Sunset Boulevard", "17380 Sunset Blvd", "1898 Westwood Blvd.", 
"3006 Sepulveda Blvd.", "514 Palisades Drive"), class = "factor"), 
    city = structure(c(1L, 1L, 2L, 2L, 2L, 3L), .Label = c("Los Angeles", 
    "Pacific Palisades", "Westwood"), class = "factor"), state = structure(c(1L, 
    1L, 1L, 1L, 1L, 1L), .Label = "CA", class = "factor")), .Names = c("street", 
"city", "state"), row.names = c(NA, -6L), class = "data.frame")

回答1:


Try mutate_if, this should also give you more control:

mutate_if(test, is.factor, as.character)



回答2:


Try this:

test[] <- lapply(test, as.character)

or this:

test <- modifyList(test, lapply(test, as.character))

or this:

test <- replace(test, TRUE, lapply(test, as.character))



回答3:


This should do the trick, it will apply the as.character function to each column of the dataframe. The apply function will return a matrix, so it just needs to be coerced to a dataframe by wrapping it with as.data.frame

test <- as.data.frame(apply(test, 2, as.character), stringsAsFactors = FALSE)


来源:https://stackoverflow.com/questions/45110199/converting-columns-to-character-with-sapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!