I want to use sapply to create a 2 columns matrix, 8 rows. First column is from 1 to 8 and second column is the square of the first. I did sapply(1:8, function(x), c(x,x^2)) so I got 8 columns and 2 rows instead of getting 2 columns and 8 rows. How can I replace columns by rows?
Try using t
> t(sapply(1:8, function(x) c(x,x^2)))
[,1] [,2]
[1,] 1 1
[2,] 2 4
[3,] 3 9
[4,] 4 16
[5,] 5 25
[6,] 6 36
[7,] 7 49
[8,] 8 64
Actually no need to use sapply for that, just use matrix
> x <- 1:8
> matrix(c(x,x^2), ncol=2)
The default for sapply is to essentially cbind the the final output. You can either tell it to not simplify or just transpose your result.
# manual rbind
do.call("rbind", sapply(1:8, function(x) c(x,x^2), simplify=FALSE))
# transpose result
t(sapply(1:8, function(x) c(x,x^2)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With