[首先,我想说我是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
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。
[从帮助中:给定一组向量,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创建。