Kenny
Kenny

Reputation: 361

R: insert values from a vector to certain columns of a matrix

I created a matrix filled with NA and then needed to put the values from a vector to the first column of that matrix. Follows is what I thought would work but it turned to be a list. May I ask why is this the case and how should I put the values in the vector to that matrix?

# matrix to be inserted values
data <- matrix(NA, nrow=30,ncol=100)

# vector with the values to be inserted to the first column of the matrix
a <- structure(list(x = c(0.541399119368356, 0.819937899117008, 0.927099622280556, 
0.746953915465998, 0.300304470460663, 0.939234765025468, 0.00364665461721936, 
0.592510805857041, 0.378149313564581, 0.731277724512969, 0.118005806632484, 
0.224750686446962, 0.565052322123529, 0.106947907333377, 0.373903635366866, 
0.322112089133453, 0.579035823594136, 0.165742979011213, 0.828820238430253, 
0.402343229302691, 0.867896472040336, 0.184151661187014, 0.464420543047166, 
0.199020364188655, 0.125166671294872, 0.0554317190348022, 0.290043442563694, 
0.716140025419364, 0.501351834671789, 0.355585063884241)), class = "data.frame", row.names = c(NA, 
-30L))

# my attempt
data[,1] <- a

Upvotes: 1

Views: 390

Answers (1)

akrun
akrun

Reputation: 887118

Based on the structure of 'a', it is a data.frame with a single column. So, we need to extract that column 'x'. Either extract ($) by name 'x' or use index a[[1]] or a[,1] or unlist(a) to a vector

data[,1] <- a$x

Upvotes: 1

Related Questions