0

I'm experiencing problem using the data.matrix() function along with lapply. I have several .csv files which I've imported in a list, and each csv file is made of 84*84 matrix. I want to replace all values in upper right half/ lower left half parts of the matrix to 0, so that it becomes approximately like this:

1100
1100
0011
0011

I figured that I should turn the dataframes to numeric matrices, and this is the code I used so far:

 files <- list.files(pattern="*.csv", full.names=F, recursive=F)
files

data1 <- lapply(files, function(x) {read.csv(x, header=F)})

data2 <- lapply(data1, function(x) replace(x,x=='NaN',0))

data3 <- lapply(data2, function(x) data.matrix(x, rownames.force = NA))

data4 <- lapply(data3, function(x) {x[c(43:84), c(1:42)] <- 0})

but the data.matrix() command doesn't seem to produce matrices, and instead it produces lists; when I check the data with class(data3[1]) , I keep getting list as the result. Also when I ran the last line, all data in data4 turned to 0.

so I tried doing this:

val1 <- data3[1]
class(val1)
val1[c(43:84), c(1:42)] <- 0

and got the following error.

val1[c(43:84), c(1:42)] <- 0
Error in val1[c(43:84), c(1:42)] <- 0 : 
  incorrect number of subscripts on matrix

I have no idea why the data.matrix() code isn't working... Would there be any way to fix the code, or another way to replace the values to 0?

Thank you in advance!

Kelly Yoo
  • 1
  • 1

0 Answers0