user459
user459

Reputation: 111

Creating data frame in R using variable

I have two data types price of type list and company of type character

price
[[1]]
[1] "Rp 83.000"

[[2]]
[1] "Rp 87.900"

[[3]]
[1] "Rp92,000"

[[4]]
[1] "Regular price  125,000.00 Discount price  125,000.00 "

and

company
[1] "Tororo"     "Babyzania"  "Bilna"      "Babylonish"

I want to create a data frame using the two data types and of the form :

Tororo Rp 83.00

Babyzania Rp 87.900

Bilna Rp 92,00

Babylonish Regular price 125,000.00 Discount price 125,000.00

Can anyone help me out i tried using directly

df=data.frame(company,price)

But it is not giving the correct dataframe I want.

Upvotes: 0

Views: 42

Answers (2)

Sven Hohenstein
Sven Hohenstein

Reputation: 81683

You can use this approach:

The data:

price <- list("Rp 83.000", "Rp 87.900", "Rp92,000",
              "Regular price  125,000.00 Discount price  125,000.00 ")
company <- c("Tororo", "Babyzania", "Bilna", "Babylonish")

Use regular expressions to create the price strings:

price2 <- sub(".*?([0-9.,]+) *$", "Rp \\1", unlist(price))
# [1] "Rp 83.000"     "Rp 87.900"     "Rp 92,000"     "Rp 125,000.00"

Create data frame:

data.frame(company, price = price2)
#      company         price
# 1     Tororo     Rp 83.000
# 2  Babyzania     Rp 87.900
# 3      Bilna     Rp 92,000
# 4 Babylonish Rp 125,000.00

Upvotes: 3

Rohit Das
Rohit Das

Reputation: 2032

If your list is exactly the same length and in the same order as your company name vector you can do this

df = data.frame(company, unlist(price))

Your 4th price is very different from the top 3 so you wont get what you printed anyway.

Upvotes: 1

Related Questions