【发布时间】:2019-09-19 06:18:18
【问题描述】:
我有一个非常宽的数据集(1,000 多列),其中大约 160 个是以下格式的对:Var1.r 和 Var1.s; Var2.r 和 Var2.s 等等。
下面是一个小例子,说明数据现在的样子:
df <- tibble(Var1.r=c("Apple", "Pear", NA), Var1.s = c(NA, NA, "Dog"),
Var2.r = c("Boat", NA, NA), Var2.s = c(NA, "Platypus", NA),
AnotherVar = c(1,2,3))
# A tibble: 3 x 5
Var1.r Var1.s Var2.r Var2.s AnotherVar
<chr> <chr> <chr> <chr> <dbl>
1 Apple NA Boat NA 1
2 Pear NA NA Platypus 2
3 NA Dog NA NA 3
我希望它看起来像什么:
> df2
# A tibble: 3 x 3
Var1 Var2 AnotherVar
<chr> <chr> <dbl>
1 Apple Boat 1
2 Pear Platypus 2
3 Dog NA 3
我编写了一个函数来合并每对列merge_columns,它以两列作为参数并返回所需的合并列。通常我会这样做:
df2 <- df %>%
mutate(Var1 = merge_cols(Var1.r, Var1.s),
Var2 = merge_cols(Var2.r, Var2.s))
然后删除所有 .r 和 .s 列。除了我不想把同一行写 80 次。
一定有更好的办法吧?
更新:我最终选择了一个丑陋但可行的解决方案。
# select all the ".s" columns
# (which will always have their .r counterparts)
to_merge <- df %>% select(ends_with(".s")) %>% names()
S <- NA
# loop through all the .s column names
for (S in to_merge) {
R <- gsub('(.+).s', '\\1.r', S) #create the equivalent .r col name
# merge them using merge_cols() and save them to the .r column
df[R] <- merge_cols(df[[S]],df[[R]])
}
# drop all the .s columns
df <- df %>% select(-ends_with(".s"))
# rename the variables that end in .r to be the "main" variable
names(df) <- gsub('(.+).r$', '\\1', names(df))
它超级难看,但它比重塑数据框工作得更快(因为我有太多列但没有那么多行),并且允许我根据我想要合并数据的方式使用自定义 merge_cols 函数。
【问题讨论】:
-
您能否指定一个输入示例和预期输出?
-
我添加了更好的示例和更多细节。感谢您的耐心等待! :)
标签: r