r - 在数据框中“带来价值”,如何?
问题描述
在下面的示例数据中,我想“带来价值”。我该如何编写代码来实现这一点?谢谢!
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
解决方案
一个选项会。将其替换为""
然后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")
推荐阅读
- sql - 如果零日不生成行/数据,如何获得每人每天的平均活动?
- mysql - 以下sql代码的语法错误是什么?
- java - 如何解决 NumberFormatException:空字符串,同时在 android 中工作而不使用任何 try and catch 异常处理程序?
- javascript - 如何将过渡效果添加到 JavaScript 切换菜单?
- python - 如何在单个 PyQt GUI 实例中多处理多个绘图
- swift - '通话中的额外参数'
- python - 我不知道如何解决这个错误,python3 语法错误'def'
- google-sheets - Google表格查询:在单元格中按日期显示数据
- qt - QT如何将样式表应用于列
- ios - Swift - 如何摆脱 UISearchController 中的这种深色背景?