如何执行计算chr和dbl

how to perform calculation chr and dbl

假设我有这个运行这个代码

df_customer %>% 
  separate(DOB,sep = "-",into = c("D", "M","Y")) %>% 
  mutate(Age=2021)

然后这个dataframe就出来了

ID      D   M   Y       G   C   Age
<int>   <   chr    >            <dbl>
268408  02  01  1970    M   4   2021
269696  07  01  1970    F   8   2021
268159  08  01  1970    F   8   2021
270181  10  01  1970    F   2   2021
268073  11  01  1970    M   1   2021
273216  15  01  1970    F   5   2021
266929  15  01  1970    M   8   2021
275152  16  01  1970    M   4   2021
275034  18  01  1970    F   4   2021
273966  21  01  1970    M   8   2021

然后,我想更改 mutate 列的列表 我如何计算类似 2021-“Y” 列的内容? 2021 是 dbl Y 是 chr

separate 中添加 convert = TRUE 应该会得到数值。您还可以使用 as.numeric 将字符转换为数字。

library(dplyr)
library(tidyr)

df_customer %>% 
  separate(DOB,sep = "-",into = c("D", "M","Y"), convert = TRUE) %>% 
  mutate(Age=2021 - as.numeric(Y))

我们可以在 base R

中做到这一点
transform(cbind(df_customer, read.table(text = df_customer$DOB, sep = "-", 
             column.names = c("D", "M", "Y"))), Age = 2021- Y)