简体   繁体   English

使用来自 Tidyverse 的 R&readr:如何将数据帧作为因子和标签导入

[英]Using R & readr from Tidyverse: How to Import dataframe as Factor and with Labels

I am using the R(-cran) & readr library from the Tidyverse.我正在使用 Tidyverse 中的 R(-cran) 和readr库。 I have a feature (column) from a .csv file that are factors, such as gender = c(0,1).我有一个来自 .csv 文件的特征(列)是因素,例如性别 = c(0,1)。

Q . How can I import the data as factors With Labels, so that they are more meaningful, For example:如何将数据导入为带标签的因子,使它们更有意义,例如:

df.csv = c("male",0,1,0,1,0) df.csv = c("男",0,1,0,1,0)

df <- read_csv("df.csv", 
               col_types = cols(male = col_factor(levels = c("0","1"), 
                                                  labels = c("F","M")))

However, I get the error:但是,我收到错误消息:

Error in col_factor(levels = c("0", "1"), labels = c("F", "M")) : 
unused argument (labels = c("F", "M"))

However, I Want: 0="F" and 1="M".但是,我想要:0="F" 和 1="M"。

Here is one way:这是一种方法:

df <- read_csv("df.csv", 
               col_types = cols(male = col_factor(levels = c("0","1"))))
# Followed by
df$column = factor(df$column, labels=c("F","M"))

str(df)

tibble [3,656 × 1] (S3: tbl_df/tbl/data.frame) tibble [3,656 × 1] (S3: tbl_df/tbl/data.frame)

$ male : Factor w/ 2 levels "F","M": 2 1 2 1 1 1 1 1 2 2 ... $ 男性:因子 w/ 2 个级别“F”、“M”:2 1 2 1 1 1 1 1 2 2 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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