仅将特定列分成表格中的多个列

问题描述 投票:0回答:1

我有一张小桌子,叫做

table_8[1:2,]

structure(list(X1 = c("", ""), X2 = c("Wealth", "Ratio (75/25)"
), X3 = c("", "Gini"), X4 = c("Non-Land Wealth", "Ratio (75/25) Gini"
), X5 = c("Income", "Ratio (75/25)"), X6 = c("", "Gini"), X7 = c("Consumption", 
"Ratio (75/25) Gini")), row.names = 1:2, class = "data.frame")

看起来像:

我需要将第二行 X4 和 X7 分成两列,这样它们看起来就像 X2 和 X3。

我已经尝试过:

table_8_n <- table_8[1:2,] |>
mutate(across(X4:X7, ~str_replace_all(.x, ") G", ")_G")))|>
separate_wider_delim(cols = c(X4,X7), names=LETTERS[1:2], names_sep = "",
                       delim="_", too_few = "align_start")

但它返回此错误:

Error in `mutate()`:
ℹ In argument: `across(X4:X7, ~str_replace_all(.x, ") G", ")_G"))`.
Caused by error in `across()`:
! Can't compute column `X4`.
Caused by error in `stri_replace_all_regex()`:
! Incorrectly nested parentheses in regex pattern. (U_REGEX_MISMATCHED_PAREN, context=`) G`)

我一直不知道该用什么来代替“穿过”。

r dplyr multiple-columns tidyr
1个回答
0
投票
table_8_n <- data.frame(lapply(table_8[1:2,], function(x) {
                      gsub(") ",")_",x)  
})) |>
  separate_wider_delim(cols = c(X4,X7), names=LETTERS[1:2], names_sep = "",
                       delim="_", too_few = "align_start") 

© www.soinside.com 2019 - 2024. All rights reserved.