akeenlogician
akeenlogician

Reputation: 179

Replacing elements of a matrix in R

I have a matrix in R that looks something like

T F T T F 
F T F T T 
T T T F F 

What I want to do is to change, say, the first 2 columns to all T's. So, I want the output to look like:

T T T T F
T T F T T
T T T F F

Is there an easy way to do this? I'm new to R, so any help is appreciated!

Upvotes: 1

Views: 449

Answers (1)

Luca Braglia
Luca Braglia

Reputation: 3243

If it's a logical matrix, use

x[,1:2] <- T

or better, a more secure (and clear)

x[,1:2] <- TRUE

why more secure? because different users can assign different values to T, eg

> T <- 0
> T == TRUE
[1] FALSE

but weird things are not allowed on TRUE:

> TRUE <- 0
Error in TRUE <- 0 : 

An example of harmful error could be in function defaults definition, eg

my.print <- function(val = T) {
    cat(val, "\n")
}

T <- "foo"

my.print()
# foo

Upvotes: 3

Related Questions