[英]How do I add a character string containing parseable fields into columns that can be added to a dataframe
我有一个数据框。 在数据帧的每一行中,最后一列是一个字符串(名为data_listing
)。 data_listing
字符串本身就是一系列由逗号分隔的键值对。 以下是其中一个字符串的示例:
> data_listing[1:2]
[1] "id:4006422,memberId:2932850,price:999,make:Chevrolet,model:Cobalt,makeYear:2009,trim:LT,mileage:142000,sellerType:For Sale By Owner,dealerOptions:null,index:2"
[2] "id:3987513,memberId:67473,price:26799,make:Audi,model:S5,makeYear:2013,trim:Prestige,mileage:44673,sellerType:Dealership,dealerOptions:{options:{VDPcarousel:true,allowUsed:true,calculator:true,carFaxIntegration:true,featuredCarousel:true,feed:true,homepageSpotlight:0,inlineSpotlight:11,limit:-1,map:true,monsterAds:true,pop:2,priceReduced:true,refresh:7,wrap:true,chat:false,inventoryComparison:true,standardFeatured:3}},index:3"
我想在数据框中为 data_listing 字符串中的每个值创建一列。 每列都将使用键值作为其名称。
如果我运行strsplit(data_listing, ",")
,那么我会得到一个字符串列表。 每个列表元素都包含一个字符向量“key:value”对。
我犹豫要写一个 for 循环来 grep 每个子列表元素并将值添加到原始数据框中的各个列,但这是我能弄清楚如何做到这一点的唯一方法。
我查看了 transform 和tidyr::separate()
,但这些都适用于字符串中的单个项目,而不是 28 个值。
你会如何解决这个问题?
我会做这样的事情:
data_listing <- c("id:4006422,memberId:2932850,price:999,make:Chevrolet,model:Cobalt,makeYear:2009,trim:LT,mileage:142000,sellerType:For Sale By Owner,dealerOptions:null,index:2",
"id:3987513,memberId:67473,price:26799,make:Audi,model:S5,makeYear:2013,trim:Prestige,mileage:44673,sellerType:Dealership,dealerOptions:{options:{VDPcarousel:true,allowUsed:true,calculator:true,carFaxIntegration:true,featuredCarousel:true,feed:true,homepageSpotlight:0,inlineSpotlight:11,limit:-1,map:true,monsterAds:true,pop:2,priceReduced:true,refresh:7,wrap:true,chat:false,inventoryComparison:true,standardFeatured:3}},index:3")
library(tidyverse)
# custom fxn for use on a single element in data_listing
parser <- function(x) {
strsplit(x, ",", ) %>%
unlist %>%
as.tibble %>%
separate(value, c("colnames", "values")) %>%
spread(colnames, values)
}
map_dfr(data_listing, parser) # apply to each element then rbind() together
# console ...
# A tibble: 2 x 28
dealerOptions id index make makeYear memberId mileage model price
<chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 null 4006422 2 Chevrolet 2009 2932850 142000 Cobalt 999
2 options 3987513 3 Audi 2013 67473 44673 S5 26799
# ... with 19 more variables: sellerType <chr>, trim <chr>, allowUsed <chr>,
# calculator <chr>, carFaxIntegration <chr>, chat <chr>, featuredCarousel <chr>,
# feed <chr>, homepageSpotlight <chr>, inlineSpotlight <chr>,
# inventoryComparison <chr>, limit <chr>, map <chr>, monsterAds <chr>, pop <chr>,
# priceReduced <chr>, refresh <chr>, standardFeatured <chr>, wrap <chr>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.