我正在尝试构建一个if函数,该函数允许我使用某个城市名称来更改数据框的“ city”列,如果该值在“邮政编码”列中以某个数字开头。
例如:如果邮政编码以1开头,则将城市列的值更改为“ NYC”, 否则,如果邮政编码以6开头,则将城市列的值更改为“芝加哥”, 否则,如果邮政编码以2开头,则将城市列的值更改为“波士顿”,
以此类推。
发件人:
city zipcode
NYC 11211
DC 20910
NYC 11104
NA 11106
NA 2008
NA 60614
收件人:
city zipcode
NYC 11211
DC 20910
NYC 11104
NYC 11106
DC 2008
Chicago 60614
这是处理NA值的一种方法:if函数将用它们已经存在的值重写相同的城市,并在有NA值的情况下键入城市名称
数据框名称data.frame
列名zipcode
和city
。
它们都是因子类型,在以后的模型中必须保持这种状态。
我想直接更改数据框,因为我将需要进一步使用它。
PS:很抱歉写得不好。我是社区的新手。
谢谢!
答案 0 :(得分:0)
这是一个可能对您有用的解决方案。
完整代码:
# load library
library(tidyverse)
# create the sample dataframe
df <- tribble(~city, ~zipcode,
'NYC',11211,
'DC',20910,
'NYC', 11104,
NA, 11106,
NA, 2008,
NA, 60614)
# change the NAs to the appropriate values
df <- df %>%
mutate(
city = case_when(
str_sub(zipcode, 1, 1) == '1' ~ 'NYC',
str_sub(zipcode, 1, 1) == '2' ~ 'DC',
str_sub(zipcode, 1, 1) == '6' ~ 'Chicago',
TRUE ~ city
)
)
# convert everything to factors
df <- df %>%
mutate(
city = as.factor(city),
zipcode = as.factor(zipcode)
)
#preview the output
glimpse(df)
glimpse()的输出是:
Observations: 6
Variables: 2
$ city <fct> NYC, DC, NYC, NYC, DC, Chicago
$ zipcode <fct> 11211, 20910, 11104, 11106, 2008, 60614
我使用的技巧是首先将所有内容保留为字符串或数字,填写缺少的值,然后转换为因数。