如果缺少值,如何使 R 从另一列中获取值?
How to make R take values from another column in case of missing values?
我有两个 table 的数据,其中包含来自不同数据源的人员离开公司的数据。在离开日期的一列中有一些缺失值,在这些情况下,我想从另一个 table.
中获取日期
两个 table 中的列如下所示:
ID exit1 exit2
1 1 N/A 31/01/2016
2 2 01/02/2016 01/01/2021
3 3 01/10/2010 30/09/2019
4 4 N/A 31/12/2015
5 5 01/01/2016 30/09/2020
我希望我的结果是这样的:
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016
有人知道我该怎么做吗?
谢谢!
我们可以使用coalesce
library(dplyr)
df1 %>%
mutate(exit1 = na_if(exit1, "N/A")) %>%
transmute(ID, exit1 = coalesce(exit1, exit2))
-输出
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016
数据
df1 <- structure(list(ID = 1:5, exit1 = c("N/A", "01/02/2016", "01/10/2010",
"N/A", "01/01/2016"), exit2 = c("31/01/2016", "01/01/2021", "30/09/2019",
"31/12/2015", "30/09/2020")), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5"))
或使用基本 R
:
df$exit1[is.na(df$exit1)] = df$exit2[is.na(df$exit1)]
如果该值是实际的字符串 "N/A"
:
df$exit1[df$exit1 == 'N/A'] = df$exit2[df$exit1 == 'N/A']
并保留所需的列:
df = df[,c('ID', 'exit1')]
这是一个使用 ifelse
语句的替代方法:
library(dplyr)
df1 %>%
mutate(exit1 = ifelse(exit1=="N/A", exit2, exit1), .keep="unused")
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016
我有两个 table 的数据,其中包含来自不同数据源的人员离开公司的数据。在离开日期的一列中有一些缺失值,在这些情况下,我想从另一个 table.
中获取日期两个 table 中的列如下所示:
ID exit1 exit2
1 1 N/A 31/01/2016
2 2 01/02/2016 01/01/2021
3 3 01/10/2010 30/09/2019
4 4 N/A 31/12/2015
5 5 01/01/2016 30/09/2020
我希望我的结果是这样的:
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016
有人知道我该怎么做吗?
谢谢!
我们可以使用coalesce
library(dplyr)
df1 %>%
mutate(exit1 = na_if(exit1, "N/A")) %>%
transmute(ID, exit1 = coalesce(exit1, exit2))
-输出
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016
数据
df1 <- structure(list(ID = 1:5, exit1 = c("N/A", "01/02/2016", "01/10/2010",
"N/A", "01/01/2016"), exit2 = c("31/01/2016", "01/01/2021", "30/09/2019",
"31/12/2015", "30/09/2020")), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5"))
或使用基本 R
:
df$exit1[is.na(df$exit1)] = df$exit2[is.na(df$exit1)]
如果该值是实际的字符串 "N/A"
:
df$exit1[df$exit1 == 'N/A'] = df$exit2[df$exit1 == 'N/A']
并保留所需的列:
df = df[,c('ID', 'exit1')]
这是一个使用 ifelse
语句的替代方法:
library(dplyr)
df1 %>%
mutate(exit1 = ifelse(exit1=="N/A", exit2, exit1), .keep="unused")
ID exit1
1 1 31/01/2016
2 2 01/02/2016
3 3 01/10/2010
4 4 31/12/2015
5 5 01/01/2016