简体   繁体   English

按顺序将 data.frame 中的所有特定值替换为另一个 data.frame 中的值 R

[英]Replace all specific values in data.frame with values from another data.frame sequentially R

I have a data.frame (df1) and I want to include a single, most recent age for each of my samples from another data.frame (df2):我有一个 data.frame (df1),我想为来自另一个 data.frame (df2) 的每个样本包含一个最近的年龄:

df1$age <- df2$age_9[match(df1$Sample_ID, df2$Sample_ID)]

The problem is that in df2 there are 9 columns for age, as each one indicates the age at a specific check-up date (age_1 is from the first visit, age_9 is the age at the 9th visit) and patients dont make all their visits.问题是在 df2 中有 9 列年龄,因为每列表示特定检查日期的年龄(age_1 是从第一次就诊开始,age_9 是第 9 次就诊时的年龄)并且患者不会进行所有就诊.

How do I add the most recently obtained age from a non empty check up date?如何从非空检查日期添加最近获得的年龄?

aka, if age_9 == "."又名,如果 age_9 == "." replace "."代替 ”。” with age_8 then if age_8 == "."与 age_8 那么如果 age_8 == "." replace "."代替 ”。” with age_7... etc与年龄_7 ...等

From this:由此:

View(df1)
Sample Age
1      50
2      .
3      .

To:至:

View(df1)
Sample Age
1      50
2      49
3      30

From the data df2从数据df2

View(df2)
Sample Age_1 Age_2 Age_3
1      40    42    44
2      35    49    .
3      30    .     .

This is my attempt:这是我的尝试:

df1$age[which(df1$age == ".")] <- df2$age_8[match(df1$Sample_ID, df2$Sample_ID)]

With base R , we can use max.col to return the last column index for each row, where the 'Age' columns are not .使用base R ,我们可以使用max.col返回每行的last列索引,其中“年龄”列不是. , cbind with sequence of rows to return a row/column index, extract the elements and change the 'Age' column in 'df1', where the 'Age' is . , cbind与行序列返回行/列索引,提取元素并更改 'df1' 中的 'Age' 列,其中 'Age' 为.

df1$Age <- ifelse(df1$Age == ".", df2[-1][cbind(seq_len(nrow(df2)), 
        max.col(df2[-1] != ".", "last"))], df1$Age)

df1 <- type.convert(df1, as.is = TRUE)

-output -输出

df1
#  Sample Age
#1      1  50
#2      2  49
#3      3  30

or using tidyverse by reshaping into 'long' format and then do a join after slice ing the last row grouped by 'Sample'或通过将tidyverse重塑为“long”格式使用 tidyverse,然后在slice将最后一行按“Sample”分组后进行连接

library(dplyr)
library(tidyr)
df2 %>% 
    mutate(across(starts_with('Age'), as.integer)) %>%
    pivot_longer(cols = starts_with('Age'), values_drop_na = TRUE) %>%
    group_by(Sample) %>% 
    slice_tail(n = 1) %>% 
    ungroup %>% 
    select(-name) %>%
    right_join(df1) %>%
    transmute(Sample, Age = coalesce(as.integer(Age), value))

-output -输出

# A tibble: 3 x 2
#  Sample   Age
#   <int> <int>
#1      1    50
#2      2    49
#3      3    30

data数据

df1 <- structure(list(Sample = 1:3, Age = c("50", ".", ".")), 
       class = "data.frame",
  row.names = c(NA, 
-3L))

df2 <- structure(list(Sample = 1:3, Age_1 = c(40L, 35L, 30L), Age_2 = c("42", 
"49", "."), Age_3 = c("44", ".", ".")), class = "data.frame", 
row.names = c(NA, 
-3L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM