sapply将列转换为字符 [英] Converting columns to character with sapply

查看:48
本文介绍了sapply将列转换为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 test ,其列为因素

I have a dataframe test whose columns are factors

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

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

如果我尝试使用 sapply()将这些列转换为字符,则出问题了,我不确定为什么

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?

以下是测试数据:

> 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")

推荐答案

尝试使用 mutate_if ,这也应该为您提供更多控制权:

Try mutate_if, this should also give you more control:

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

这篇关于sapply将列转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆