Appending a vector inside a double for loop in R - r

I am trying to edit the values inside a vector determined before the loop. I want to append every element in the vector sequentially but can't figure out how to do it.
So here I tried
hr <- seq(0,5,1)
hr2 = hr
vec <- vector("list",length = length(hr)^2)
for (x in seq(hr)) {
for (i in seq(hr2)) {
vec[[x]] <- i +1
}
}
But this just edits the first 6 elements of the list. I would like to update element 1, then 2, then 3,.... finally element 36.
EDIT: The expected output would be a vector of length 36 with values in each element

Related

How to treat a single row of matrix in R as a matrix object

I have an R script that removes random rows from an nxm (n row, m column) matrix depending on which elements occur in a data set. I have a conditional statement that terminates if there are no rows remaining. This works fine if there are 0 rows, but not if there is one.
For example, if I have
m1 = rbind(c(1,2),c(1,4),c(2,3),c(2,4))
and I delete all rows
m1 = m1[-c(1,2,3,4),]
the conditional statement
if(length(m1[,1]) > 0)
evaluates correctly to FALSE and the program terminates, since the object m1 is a 0x2 matrix. However, if I delete all but one row, e.g.
m1 = m1[-c(1,2,4),]
the same conditional statement does not evaluate because the remaining row is no longer treated as a matrix object of dimension 1xn, but rather as a numeric vector, so dim, length(m[,1]) etc are undefined.
Is there some way to preserve a single row as a 1xn matrix object, other than checking if only a single row remains and applying t(as.matrix(m1)), which would be a very clumsy approach?
I've appended my complete script below, but the details of the script shouldn't be necessary to address this question. The while(temp_mat[,1] > 0) is the step that breaks if I have a single row (but works fine if there are none or any number of rows > 1)
seq_to_mask = function(mat){
temp_mat = mat
to_mask = c()
iter = 0
while(length(temp_mat[,1])>0){
all_instances = c(temp_mat[,1],temp_mat[,2])
#number of times a sample appears
occurrences = sort(table(all_instances))
max_instances = as.numeric(names(occurrences)[length(occurrences)])
posits = which(temp_mat[,1]==max_instances | temp_mat[,2]==max_instances)
to_mask = c(to_mask, max_instances)
temp_mat = temp_mat[-posits,]
iter = iter + 1
}
return(to_mask)
}
The reason seems to be the coercion of matrix to vector when there is a single row/column. We can use drop = FALSE (by default it is drop = TRUE)
m1 <- m1[-c(1, 2, 4), , drop = FALSE]

R - Given a List of Vectors replace values in Vectors for each Vector with LOOP

Here is the set up. I have vec1 containing 5 numbers. I also have h5-h9 as a vector of 800 elements. The knot_list is a list of h5-h9 vectors containing 800 0's per h vector. Given x, I want to replace each h5,h6,h7,h8,h9's 800 elements with the formula x-(vec[i]) where i is 1:5 in this case.
vec1 <- c(1, 2, 3,4,5)
vec1 <- list(vec1) # needed for my real code
h5=rep(0,800);h6=h5;h7=h5;h8=h5;h9=h5
list_knot<- list(h5,h6,h7,h8,h9)
list_length <- length(list_knot) # 5
x=seq(from=1,to=800,length.out=800)
Is there a way to make the formula described above replace each vector value in each element of the list? I tried doing for loops, but syntax is wrong.
for (i in 1:list_length){
print(i)
for (j in 1:length(seq(0,800))){
list_knot[[i]][[j]] = x-vec1[[1]][[i]]^3
}
}
The list_knot is set up where it is a list containing 5 vectors. Each vector has 800 0's that need to be replaced by the formula. How can I do this?
It seems to me that this is what you are looking for
vec1 <- list(c(1, 2, 3, 4, 5)) # as per your requirement
list_knot <- lapply(vec1[[1]], function(v, x) x - v^3, x = 1:800)
, i.e., subtract each element of vec1 from the same x (1:800) and return a list of vectors. As you would like to replace every single element for each h in list_knot, you might just drop that list completely and construct a new one.

Fill a matrix using R *apply functions

I have a matrix with that needs to be filled up with values. The first row of the matrix will have the same value and the subsequent row values would be generated using a function based on the first row value
I can do this using nested for loop like this. The outer loop goes over the column, sets the first row in that column to value. Then the inner loop fills up the rest of the rows in that column using the fn. The function itself takes the previous row value as its input.
fn <- function(value){ value + 1 }
myMatrix <- matrix(NA,5,3)
value <- 100
for(col in 1:ncol(myMatrix)){
myMatrix[1,col]<-value #First row value for all the columns should be the same
for(row in 2:nrow(myMatrix)){
#Rest of the row values generated using fn
myMatrix[row,col] <- fn(myMatrix[row-1,col])
}
}
myMatrix
I don't want to use a for loop and would like to specifically achieve this using one of R's vectorized *apply functions. I tried this but its not working.
fn <- function(value){ value + 1 }
myMatrix2 <- matrix(NA,5,3)
value <- 100
sapply(1:ncol(myMatrix2), function(col){
myMatrix2[1,col]<-value
sapply(2:nrow(myMatrix2),function(row){
fn(myMatrix2[row-1,col])
})
})
EDIT :
I was able to achieve it using sapply and the <<- assignment operator for filling up the matrix. But, is there a more cleaner/efficient way to do it using the *apply family ?
fn <- function(value){ value + 1 }
myMatrix2 <- matrix(NA,5,3)
value <- 100
myMatrix2[1,]<-value #first row of the matrix to have the same value
sapply(1:ncol(myMatrix2), function(col){
sapply(2:nrow(myMatrix2),function(row){
myMatrix2[row,col] <<- fn(myMatrix2[row-1,col])
})
})
myMatrix2

How to locate specific elements in one matrix and compare those with a second matrix?

Let's have a binary Matrix/ Data Frame:
library("Matrix")
df_binary <- data.frame(as.matrix(rsparsematrix(1000, 20,nnz = 800, rand.x = runif)))
df_binary[df_binary > 0] = 1
Now, I would like to create an index-object of all elements of equal value 1. How I can do this in R?
I need something like an index of those entries to compare the entries of the binary matrix with entries of a second matrix. Both matrices are of the same size - if this information could be important.
If you want a list out you could do something along the lines of
list_ones <- function(df) {
out <- list()
for (col in names(df)) {
out[[col]] <- which(df[[col]] == 1)
}
return(out)
}
list_ones(df_binary)

Assign a value to character named variable with index

I know we can use assign to assign values to a character name vector. For example
assign("target",1:5)
However, if we want to change the 1st element of the target(target can be a vector/matrix/list), how should we do that? target here can also be a matrix, so we can change one element, one row or one column.
I want to do something like
target[1] <- 99
if I use
assign("target[1]",99)
it will only generate a new object named target[1] and value is 99. Here is a simple and trial example
# This function is meaningless, just used to show my situation
# variable_name is a character
example_function <- function(variable_name){
assign(variable_name,1:5)
if(rnorm(1)>1){
variable_name[1] <- 99 #This will not work and I just need some function to achive this purpose
}
}
example_function("justAname")
As an alternative approach you could use the [<- function.
f = function(variable_name){
assign(variable_name,1:5)
if(rnorm(1)>1){
`[<-`(eval(as.name(variable_name)),i = 1, value = 99)
}
get(variable_name)
}
This should also work with matrices
f_mat = function(variable_name){
assign(variable_name,matrix(1:25,nrow = 5))
if(rnorm(1)>1){
`[<-`(eval(as.name(variable_name)),i = 1, j = , value = 99) # for 1st row
# `[<-`(eval(as.name(variable_name)),i = , j = 1, value = 99) # for 1st col
#specify i and j for ith row jth column
}
get(variable_name)
}
and lists similarly.

Resources