[英]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.