更改多列的类 [英] Change the class of multiple columns

查看:66
本文介绍了更改多列的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8列40行的数据框。所有列均具有数值。我需要将第1列到第5列更改为字符。我尝试了 dplyr :: mutate_at(),但无法正常工作。我不想创建新列,但要更改现有列的类。我不断收到错误
col1 的长度必须为40(行数)或一个,而不是0

I have a data frame with 8 columns and 40 rows. All columns have numeric values. I need to change column 1 to 5 to character. I tried dplyr::mutate_at() but I cannot get it to work. I don't want to create new columns, but change the class of the existing ones. I keep getting the error Column col1 must be length 40 (the number of rows) or one, not 0

用dplyr进行此操作的正确方法是什么?
我想我可以做

What is the right way to do this with dplyr? I guess I could just do

df $ col1 <-as.character(df $ col1)

每列,但我想学习dplyr的功能。

for each of the columns, but I would like to learn the power of dplyr.

任何帮助总是很感激。谢谢!!

Any help is always appreciated. Thanks!!

推荐答案

尝试按以下方式操作:

df <- data.frame(a = c(0, 0, 0), b = c(1, 1, 1), c = c(0, 0, 1), d = c(1, 1, 1), e = c(0, 0, 0))

df_updated <- df %>% mutate_at(vars(1:5), as.character)

这篇关于更改多列的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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