嗨,我有一个混乱的数据框架如下:
df <- data.frame(age.band = c("0-5","5-10"), beg.code = c("A1","B1"), end.code=c("A5","B3"),value = c(10,5))
age.band beg.code end.code value
0-5 A1 A5 10
5-10 B1 B3 5
我想把它转变成一种更友好的格式,例如:
index age.band value
A1 0-5 10
A2 0-5 10
A3 0-5 10
A4 0-5 10
A5 0-5 10
B1 5-10 5
B2 5-10 5
B3 5-10 5
有人能帮我找到一种方法来为这个数据文件添加所有缺失的索引吗?谢谢
发布于 2017-12-21 01:17:28
使用德普利和提尔的解决方案。我添加了stringsAsFactors = FALSE
以避免在创建示例数据框架时创建因素列。如果在原始数据框架上运行代码,则会收到因因素列引起的警告消息,但不会影响最终结果。
library(dplyr)
library(tidyr)
df2 <- df %>%
gather(Code, Value, ends_with("code")) %>%
extract(Value, into = c("Group", "Index"), regex = "([A-Za-z+].*)([\\d].*$)",
convert = TRUE) %>%
select(-Code) %>%
group_by(Group) %>%
complete(Index = full_seq(Index, period = 1)) %>%
unite(Index, c("Group", "Index"), sep = "") %>%
fill(-Index)
df2
# # A tibble: 8 x 3
# Index age.band value
# * <chr> <chr> <dbl>
# 1 A1 0-5 10
# 2 A2 0-5 10
# 3 A3 0-5 10
# 4 A4 0-5 10
# 5 A5 0-5 10
# 6 B1 5-10 5
# 7 B2 5-10 5
# 8 B3 5-10 5
数据
df <- data.frame(age.band = c("0-5","5-10"), beg.code = c("A1","B1"), end.code=c("A5","B3"),value = c(10,5),
stringsAsFactors = FALSE)
发布于 2017-12-21 03:08:18
下面是base R
的一个选项。这样做的目的是从“代码”列中删除非数字字符,将其转换为numeric
,并获取存储为list
的序列。然后,对非数字字符进行paste
,最后,基于list
的lengths
,使用rep
展开原始数据集的行,并通过对list
进行unlist
来创建一个新的列“索引”。
lst <- do.call(Map, c(f = `:`, lapply(df[2:3], function(x) as.numeric(sub("\\D+", "", x)))))
lst1 <- Map(paste0, substr(df[,2], 1, 1), lst)
data.frame(index = unlist(lst1), df[rep(seq_len(nrow(df)), lengths(lst1)), -(2:3)])
https://stackoverflow.com/questions/47916404
复制相似问题