gpt4 book ai didi

r - 拆分R中不同列中的值

转载 作者:行者123 更新时间:2023-12-04 08:48:19 25 4
gpt4 key购买 nike

我的数据集中的一列包含如下值

utm_source=google&utm_medium=cpc&utm_campaign=1234567&utm_term=brand%20&utm_content=Brand&gclid=ERtyuiipotf_YTj

我应该如何将其与 R 中的值拆分为不同的列?
utm_source utm_medium  utm_campaign utm_brand  utm_content
google cpc 1234567 brand%20 Brand
dput(column) 给出以下输出
structure(list("null", "gclid=ertyyhglkdl-kjkY", 
"utm_source=google&utm_medium=cpc&utm_campaign=1234556&utm_term=brand%20shirts&utm_content=Brand&gclid=jhajsgjdgd_ajs",
"utm_source=google&utm_medium=cpc&utm_campaign=1674814043&utm_term=brand%20shirts&utm_content=Brand&gclid=KvgMsEAAYASAAEgLq6vD_BwE",
"null", "null", "null", "null", "null", "null", "null", "null",
"null", "null", "utm_source=fb&utm_medium=ctw&utm_campaign=Shirt_rem&utm_content=CasciaShirt"), class = c("extracted",
"list"))

最佳答案

我不确定这是否是预期的输出。以下可能是您目标的基本 R 选项

Reduce(
function(...) merge(..., all = TRUE),
lapply(
column,
function(x) {
u <- unlist(strsplit(x, "&"))
setNames(data.frame(as.list(gsub(".*=", "", u))), gsub("=.*", "", u))
}
)
)
这使
  utm_source utm_medium utm_campaign utm_content null                    gclid
1 fb ctw Shirt_rem CasciaShirt <NA> <NA>
2 google cpc 1234556 Brand <NA> jhajsgjdgd_ajs
3 google cpc 1674814043 Brand <NA> KvgMsEAAYASAAEgLq6vD_BwE
4 <NA> <NA> <NA> <NA> null ertyyhglkdl-kjkY
utm_term
1 <NA>
2 brand%20shirts
3 brand%20shirts
4 <NA>

更新
如果您想保留所有数据,即使是 null ,你可以试试下面的代码
Reduce(
function(x, y) {
if (all(is.na(x)) | all(is.na(y))) {
return(rbind(x, y))
}
dplyr::full_join(x, y)
},
lapply(
column,
function(x) {
if (x == "null") {
return(NA)
}
u <- unlist(strsplit(x, "&"))
setNames(data.frame(as.list(gsub(".*=", "", u))), gsub("=.*", "", u))
}
)
)
这使
                      gclid utm_source utm_medium utm_campaign       utm_term
1 <NA> <NA> <NA> <NA> <NA>
2 ertyyhglkdl-kjkY <NA> <NA> <NA> <NA>
3 jhajsgjdgd_ajs google cpc 1234556 brand%20shirts
4 KvgMsEAAYASAAEgLq6vD_BwE google cpc 1674814043 brand%20shirts
5 <NA> <NA> <NA> <NA> <NA>
6 <NA> <NA> <NA> <NA> <NA>
7 <NA> <NA> <NA> <NA> <NA>
8 <NA> <NA> <NA> <NA> <NA>
9 <NA> <NA> <NA> <NA> <NA>
10 <NA> <NA> <NA> <NA> <NA>
11 <NA> <NA> <NA> <NA> <NA>
12 <NA> <NA> <NA> <NA> <NA>
13 <NA> <NA> <NA> <NA> <NA>
14 <NA> <NA> <NA> <NA> <NA>
15 <NA> fb ctw Shirt_rem <NA>
utm_content
1 <NA>
2 <NA>
3 Brand
4 Brand
5 <NA>
6 <NA>
7 <NA>
8 <NA>
9 <NA>
10 <NA>
11 <NA>
12 <NA>
13 <NA>
14 <NA>
15 CasciaShirt

关于r - 拆分R中不同列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64199683/

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