Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a 2 columns, 8 rows matrix instead of returning 2 rows, 8 columns matrix using sapply?

Tags:

r

sapply

matrix

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?

like image 623
Nour Avatar asked Nov 30 '25 12:11

Nour


2 Answers

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)
like image 74
Jilber Urbina Avatar answered Dec 02 '25 02:12

Jilber Urbina


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)))     
like image 37
cdeterman Avatar answered Dec 02 '25 04:12

cdeterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!