用于数据框以填充另一个数据框的缺失值

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

[首先,我想说我是R的新手。这个问题令人难以置信。我试过了apply,lapply和mapply。都有错误。我迷路了。

我想做的是从“结果”中抽出时间,并将其放在“记录”中的时间中。[[IF记录没有时间(在这里是不适用)。

我已经在传统的for循环中完成了此操作,但它使代码难以阅读。我已经阅读了Apply函数可以使此操作更容易。

Data Frame "Results" ID Time(sec) 1 1.7169811 2 1.9999999 3 2.3555445 4 3.4444444 Data Frame "Records" ID Time(sec) Date 1 NA 1/1/2018 2 1.9999999 1/1/2018 3 NA 1/1/2018 4 3.1111111 1/1/2018 Data Frame 'New' Records ID Time(sec) Date 1 1.7169811 1/1/2018 2 1.9999999 1/1/2018 3 2.3555445 1/1/2018 4 3.1111111 1/1/2018

r dataframe na
2个回答
1
投票
在这种情况下无需使用。基于某些谓词在两个值之间有条件选择的模式是ifelse()

ifelse(predicate, value_a, value_b)

在这种情况下,您还必须确保两个数据帧之间的值与ID匹配。在R中实现此功能的函数适当命名为match()

match(target_values, values_to_be_matched)

match返回按如下方式与values_to_be_matched匹配到target_values的索引:target_values[indices]

将其组合在一起:

inds <- match(records$ID, results$ID) records$time <- ifelse(is.na(records$time), results$time[inds], records$time)

is.na()这是一个谓词,用于检查向量中每个值的值是否均为NA。

2
投票
受此answer的启发。

[从帮助中:给定一组向量,coalesce()查找每个位置的第一个非缺失值。这是受SQL COALESCE函数启发的,该函数对NULL执行相同的操作

library(tidyverse) txt1 <- "ID Time(sec) 1 1.7169811 2 1.9999999 3 2.3555445 4 3.4444444" txt2 <- "ID Time(sec) Date 1 NA 1/1/2018 2 1.9999999 1/1/2018 3 NA 1/1/2018 4 3.1111111 1/1/2018" df1 <- read.table(text = txt1, header = TRUE) df2 <- read.table(text = txt2, header = TRUE) df1 %>% left_join(df2, by = "ID") %>% mutate(Time.sec. = coalesce(Time.sec..x, Time.sec..y)) %>% select(-Time.sec..x, -Time.sec..y) #> ID Date Time.sec. #> 1 1 1/1/2018 1.716981 #> 2 2 1/1/2018 2.000000 #> 3 3 1/1/2018 2.355545 #> 4 4 1/1/2018 3.444444

由reprex软件包(v0.2.0)于2018-03-10创建。
© www.soinside.com 2019 - 2024. All rights reserved.