根据 R 中的条件将数字数据转换为字符

问题描述 投票:0回答:1

我有一个月份的数字数据列,所以我想将该列转换为字符类型,同时也将值更改为字母。

all_trips %>%
 as.character(all_trips$ride_months == 1) <- 'jan'

它给出了一个错误:as.character(all_trips$ride_month == 1) 中的错误<- "jan" : could not find function "as.character<-"

r character numeric
1个回答
0
投票

我会通过简单的合并来分配作业,例如

all_trips <- data.frame(ride_months=sample(12,10))

table <- data.frame(month_num = seq(1,12,1), 
                    month_str = c("jan", "feb", "mar", "apr", "mai", "jun", 
                                  "jul", "aug", "sep", "oct", "nov", "dec"))


df = merge(all_trips, table, by.x="ride_months", by.y="month_num", sort=FALSE)

   ride_months month_str
1            4       apr
2            5       mai
3            9       sep
4            7       jul
5            3       mar
6            1       jan
7           11       nov
8           10       oct
9            2       feb
10           8       aug

然后您可以简单地覆盖数据框中的旧列。例如

all_trips$ride_months <- df$month_str
© www.soinside.com 2019 - 2024. All rights reserved.