Andrew Linares
Andrew Linares

Reputation: 1

Access value within list that is within a data frame

I am working with a data frame of lists. I want to access the text value within the list (df$Promoted) and create a new column that holds these values. I have tried unlist() which only returns the value 1 for each observation.

df$Promoted 

Promoted
c(jumbobagpinkpolkadot = 1)
c(vintagesnapcards = 1)
c(bakingsetpieceretrospot = 1)
c(doormatkeepcalmandcomein = 1)
c(setofcaketinspantrydesign = 1)
c(vintagechristmasbunting = 1)

I am looking to have the following column:

df$Promoted2
jumbobagpinkpolkadot
vintagesnapcards
bakingsetpieceretrospot
doormatkeepcalmandcomein
setofcaketinspantrydesign
vintagechristmasbunting
dput(df)

structure(list(Promoted = list(c(setofribbonsvintagechristmas = 1L), 
    c(jumbobagvintageleaf = 1L), c(lunchbagblackskull = 1L), 
    c(doormatkeepcalmandcomein = 1L), c(spaceboybirthdaycard = 1L), 
    c(vintagechristmasbunting = 1L))), class = "data.frame", row.names = c(NA, 
-6L))

Upvotes: 0

Views: 45

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389325

You can use stack :

data <- stack(unlist(df$Promoted))
names(data) <- c('Promoted', 'Promoted2')
data

#  Promoted                    Promoted2
#1        1 setofribbonsvintagechristmas
#2        1          jumbobagvintageleaf
#3        1           lunchbagblackskull
#4        1     doormatkeepcalmandcomein
#5        1         spaceboybirthdaycard
#6        1      vintagechristmasbunting

str(data)
#'data.frame':  6 obs. of  2 variables:
# $ Promoted : int  1 1 1 1 1 1
# $ Promoted2: Factor w/ 6 levels "setofribbonsvintagechristmas",..: 1 2 3 4 5 6

Upvotes: 0

gsolomon10
gsolomon10

Reputation: 365

We could use some regex for this:

df$Promoted2 <- gsub(".*\\((.*) = 1\\).*", "\\1", df$Promoted)

> df$Promoted2
[1] "setofribbonsvintagechristmas" "jumbobagvintageleaf"          "lunchbagblackskull"          
[4] "doormatkeepcalmandcomein"     "spaceboybirthdaycard"         "vintagechristmasbunting" 

Upvotes: 1

Related Questions