1

How to create a data frame in R providing the data row-wise? I am looking for a one statement solution.

This is the one statement solution for column-wise:

mydf = data.frame(
    fruit = c("apple", "orange", "banana"),
    pieces = c(3, 2, 5)
)

I find the row-wise approach more logical (imagine that we have hundreds of entries), therefore I am looking for such a solution.

I made some investigations. The simplest solution I found is this:

mymatrix <- rbind(
    c("apple", 3), 
    c("orange", 2), 
    c("banana", 5)
)
colnames(mymatrix) <- c("fruit", "pieces")
mydf = as.data.frame(mymatrix)
mydf = transform(mydf, pieces=as.numeric(pieces))

But as an extra variable and multiple step transformation is needed, I still find it too complicated. Is there a one statement solution to that, similar to the column-wise approach?

1
  • 1
    tribble()? tibble() %>% add_row(fruit="Orange", pieces=3)? Commented Mar 21, 2021 at 8:41

1 Answer 1

1

You can use tribble from tibble package for Row-wise tibble creation

library(tibble)

mydf <- tribble(
~fruit, ~pieces, 
"apple", 3, 
"orange", 2,
"banana", 5
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.