0

I am new(ish) to R and I am still unsure about loops.

If I had a large matrix object in R with columns having values of 0 - 4, and I would like to invert these values for specified columns.

I would use the code:

b[, "AX1"] <- 4 - b[, "AX1"]

Where b is a Matrix extracted from a larger list object and AX1 would be a column in the matrix.

I would then replace the changed Matrix back into its list using the code:

DF1$geno[[1]]$data <- b 

How would I loop this code through a list of column names(AX1, AX10, AX42, ...)for about 30 columns of the 5000 columns in the matrix if I used a list with the 30 Column names to be inverted?

utubun
  • 4,400
  • 1
  • 14
  • 17
  • 1
    It helps others to answer your question if you provide a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – utubun Aug 20 '21 at 08:55

2 Answers2

1

The simplest way you can do it (assuming that you always transform it the way x = 4 - x) is to expand your approach to the list of columns:

# Create an example dataset

set.seed(68859457)

(
    dat <- matrix(
        data = sample(x = 0:4, size = 100, replace = TRUE),
        nrow = 10,
        dimnames = list(1:10, paste('AX', 1:10, sep = ''))
    )
)

#    AX1 AX2 AX3 AX4 AX5 AX6 AX7 AX8 AX9 AX10
# 1    2   1   2   3   2   2   3   1   0    4
# 2    4   3   4   4   0   1   3   1   3    4
# 3    3   0   3   4   2   2   4   1   2    1
# 4    2   2   0   2   4   2   2   1   1    0
# 5    4   4   4   3   3   1   0   3   2    2
# 6    2   1   1   0   3   3   4   4   1    0
# 7    2   3   1   3   3   1   0   1   0    4
# 8    2   2   1   1   0   3   1   3   2    1
# 9    3   1   4   1   2   1   0   0   4    1
# 10   4   3   2   4   1   0   2   0   3    2

# Create a list of columns you want to modify

set.seed(68859457)

(
    cols_to_invert <- sort(sample(x = colnames(dat), size = 5))
)

# [1] "AX3" "AX4" "AX5" "AX6" "AX9"

# Use the list of columns created above to modify matrix in place

dat[, cols_to_invert] <- 4 - dat[, cols_to_invert]

# See the result

dat

#    AX1 AX2 AX3 AX4 AX5 AX6 AX7 AX8 AX9 AX10
# 1    2   1   2   1   2   2   3   1   4    4
# 2    4   3   0   0   4   3   3   1   1    4
# 3    3   0   1   0   2   2   4   1   2    1
# 4    2   2   4   2   0   2   2   1   3    0
# 5    4   4   0   1   1   3   0   3   2    2
# 6    2   1   3   4   1   1   4   4   3    0
# 7    2   3   3   1   1   3   0   1   4    4
# 8    2   2   3   3   4   1   1   3   2    1
# 9    3   1   0   3   2   3   0   0   0    1
# 10   4   3   2   0   3   4   2   0   1    2
utubun
  • 4,400
  • 1
  • 14
  • 17
0

Difficult to tell without knowing exact structure of the data but based on your explanation and attempt maybe this will help.

cols <- c('AX1', 'AX10', 'AX42')

DF1$geno <- lapply(DF1$geno, function(x) {
  x$data <- 4 - x$data[, cols]
  x
})
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213