如何将值从一个 Dataframe 插入到另一个 Dataframe

ttisahbt  于 2023-01-18  发布在  其他
关注(0)|答案(2)|浏览(140)

一个类似我的数据是:

dat1<-read.table (text=" ID Rat Garden  Class   Time1   Time2   Time3
1   12  12  0   15  16  20
1   13  0   1   NA  NA  NA      
2   13  11  0   18  12  16
2   9   0   1   NA  NA  NA      
1   6   13  0   17  14  14
1   7   0   2   NA   NA  NA     
2   4   14  0   17  16  12
2   3   0   2   NA  NA  NA      

", header=TRUE)
 
dat2<-read.table (text=" ID Value1  Value2
1   6   7
2   5   4
", header=TRUE)

我想把dat2到dat1的值插入到Time1列中,在class列中的数字1和2之前,我得到了以下结果。

ID  Rat Garden  Class   Time1   Time2   Time3
1   12  12  0   15  16  20
1   13  0   1   6       
2   13  11  0   18  12  16
2   9   0   1   5       
1   6   13  0   17  14  14
1   7   0   2   7       
2   4   14  0   17  16  12
2   3   0   2   4
3npbholx

3npbholx1#

我们可以按"ID"和replace分组,其中NA值与ID匹配的unlist ed "dat2""Value"列一起出现

library(dplyr)
dat1 %>% 
   group_by(ID) %>%
   mutate(Time1 = replace(Time1, is.na(Time1), 
     unlist(dat2[-1][dat2$ID == cur_group()$ID,]))) %>%
   ungroup
  • 输出
# A tibble: 8 × 7
     ID   Rat Garden Class Time1 Time2 Time3
  <int> <int>  <int> <int> <int> <int> <int>
1     1    12     12     0    15    16    20
2     1    13      0     1     6    NA    NA
3     2    13     11     0    18    12    16
4     2     9      0     1     5    NA    NA
5     1     6     13     0    17    14    14
6     1     7      0     2     7    NA    NA
7     2     4     14     0    17    16    12
8     2     3      0     2     4    NA    NA
waxmsbnn

waxmsbnn2#

这是一个狂野的旅程:首先,我们将dat2中的值作为一个向量取出,然后将交替的NA放入向量中,直到列长为dat1,最后在cbind之后使用coalesce

library(dplyr)
library(tidyr)

vector <- dat2 %>% 
  pivot_longer(-ID) %>% 
  arrange(name) %>% 
  pull(value)
      
col_x <- c(sapply(vector, c, rep(NA, 1)))

cbind(dat1, col_x) %>% 
  mutate(col_x = lag(col_x)) %>% 
  mutate(Time1= coalesce(Time1, col_x), .keep="unused")
ID Rat Garden Class Time1 Time2 Time3
1  1  12     12     0    15    16    20
2  1  13      0     1     6    NA    NA
3  2  13     11     0    18    12    16
4  2   9      0     1     5    NA    NA
5  1   6     13     0    17    14    14
6  1   7      0     2     7    NA    NA
7  2   4     14     0    17    16    12
8  2   3      0     2     4    NA    NA

相关问题