将所有列转换为data.frame中的字符 [英] Convert all columns to characters in a data.frame

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

问题描述

考虑具有多种数据类型的data.frame.

Consider a data.frame with a mix of data types.

出于奇怪的目的,用户需要将所有列都转换为字符.最好怎么做?解决问题的尝试是这样的:

For a weird purpose, a user needs to convert all columns to characters. How is it best done? A tidyverse attempt at solution is this:

map(mtcars,as.character) %>% map_df(as.list) %>% View()
c2<-map(mtcars,as.character) %>% map_df(as.list)

当我呼叫 str(c2)时,应该说出带有所有字符的小标题或data.frame.

when I call str(c2) it should say a tibble or data.frame with all characters.

另一个选项是 write.csv() write_csv()中的一些参数设置,以在生成的文件输出中实现相同的目的.

The other option would be some parameter settings for write.csv() or in write_csv() to achieve the same thing in the resulting file output.

推荐答案

2021-03-01

从dplyr 1.0.0开始, _all()函数变体被取代.实现此目的的新方法是使用新的 across()函数.

Beginning with dplyr 1.0.0, the _all() function variants are superceded. The new way to accomplish this is using the new across() function.

library(dplyr)
mtcars %>%
  mutate(across(everything(), as.character))

使用 across(),我们选择要使用整理选择助手(这里我们使用 everything()选择所有列),然后指定要应用于每个选定列的函数.在这种情况下,这就是 as.character().

With across(), we choose the set of columns we want to modify using tidyselect helpers (here we use everything() to choose all columns), and then specify the function we want to apply to each of the selected columns. In this case, that is as.character().

原始答案:

您还可以使用 dplyr :: mutate_all .

library(dplyr)
mtcars %>%
  mutate_all(as.character)

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

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