Reputation: 473
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?
Upvotes: 1
Views: 227
Reputation: 79276
You can use tribble
from tibble
package for Row-wise tibble creation
library(tibble)
mydf <- tribble(
~fruit, ~pieces,
"apple", 3,
"orange", 2,
"banana", 5
)
Upvotes: 1