gpt4 book ai didi

r - 根据行类型填充列中的值

转载 作者:行者123 更新时间:2023-12-03 23:59:23 24 4
gpt4 key购买 nike

我有一个数据农场:

ID      Type     Direction
1 A Rigth
1 B Rigth
2 AC Left
2 BC Right
3 C Right
1 A NA
1 B NA
2 AC NA
2 BC NA
3 C NA
1 A NA
1 B NA
2 AC NA
2 BC NA
3 C NA

我想根据行的 ID 和类型在列方向中填充那些 NA(方向不为空的情况)。所以想要的结果必须是这样的:

ID      Type     Direction
1 A Rigth
1 B Rigth
2 AC Left
2 BC Right
3 C Right
1 A Rigth
1 B Rigth
2 AC Left
2 BC Right
3 C Right
1 A Rigth
1 B Rigth
2 AC Left
2 BC Right
3 C Right

我该怎么做?

最佳答案

我们可以通过 'ID'、Type' 和 fill

进行分组
library(dplyr)
library(tidyr)
df1 %>%
group_by(ID, Type) %>%
fill(Direction)

-输出

# A tibble: 15 x 3
# Groups: ID, Type [5]
# ID Type Direction
# <int> <chr> <chr>
# 1 1 A Rigth
# 2 1 B Rigth
# 3 2 AC Left
# 4 2 BC Right
# 5 3 C Right
# 6 1 A Rigth
# 7 1 B Rigth
# 8 2 AC Left
# 9 2 BC Right
#10 3 C Right
#11 1 A Rigth
#12 1 B Rigth
#13 2 AC Left
#14 2 BC Right
#15 3 C Right

数据

df1 <- structure(list(ID = c(1L, 1L, 2L, 2L, 3L, 1L, 1L, 2L, 2L, 3L, 
1L, 1L, 2L, 2L, 3L), Type = c("A", "B", "AC", "BC", "C", "A",
"B", "AC", "BC", "C", "A", "B", "AC", "BC", "C"), Direction = c("Rigth",
"Rigth", "Left", "Right", "Right", NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA)), class = "data.frame", row.names = c(NA, -15L))

关于r - 根据行类型填充列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64054518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com