简体   繁体   中英

Create R data frame row-wise

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?

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

library(tibble)

mydf <- tribble(
~fruit, ~pieces, 
"apple", 3, 
"orange", 2,
"banana", 5
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM