首页 > 解决方案 > 在数据框中“带来价值”,如何?

问题描述

在下面的示例数据中,我想“带来价值”。我该如何编写代码来实现这一点?谢谢!

df
  id period q1 q2 q3
1  1      1  1  2  4
2  1      2         
3  1      3         
4  2      1  3  1  9
5  2      2  7  8  6
6  2      3         
7  3      1  5  7  3
8  3      2         
9  3      3   

它应该看起来像:

  id period q1 q2 q3
1  1      1  1  2  4
2  1      2  1  2  4
3  1      3  1  2  4
4  2      1  3  1  9
5  2      2  7  8  6
6  2      3  7  8  6
7  3      1  5  7  3
8  3      2  5  7  3
9  3      3  5  7  3

标签: r

解决方案


一个选项会。将其替换为""然后NA使用fill

library(dplyr)
library(tidyr)
df1 %>%
     mutate_at(vars(starts_with('q')), na_if, "") %>%
     group_by(id) %>%
     fill(starts_with('q'))
# A tibble: 9 x 5
# Groups:   id [3]
#     id period q1    q2    q3   
#  <int>  <int> <chr> <chr> <chr>
#1     1      1 1     2     4    
#2     1      2 1     2     4    
#3     1      3 1     2     4    
#4     2      1 3     1     9    
#5     2      2 7     8     6    
#6     2      3 7     8     6    
#7     3      1 5     7     3    
#8     3      2 5     7     3    
#9     3      3 5     7     3    

数据

df1 <- structure(list(id = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), period = c(1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), q1 = c("1", "", "", "3", "7", 
"", "5", "", ""), q2 = c("2", "", "", "1", "8", "", "7", "", 
""), q3 = c("4", "", "", "9", "6", "", "3", "", "")), row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9"), class = "data.frame")

推荐阅读