0

I have a matrix of which I want to edit one of the columns based on another of the columns. The column I want to edit has numeric values and the reference column has string values.

I have a matrix that looks like this:

M = matrix(c(1,4,7,6,5,a,b,c,a,b),5,2) 1 a 4 b 7 c 6 a 5 b 

And I want to multiply by a factor the rows where the second column has the "a" value, to get a matrix like this (for example by multiplying by 2):

2 a 4 b 7 c 12 a 5 b 
1
  • 1
    Sidenote: A matrix can hold only 1 type, characters in your case. Maybe you need a data frame/list ? Also those letters should probably be quoted. "a", "b" etc. Commented Feb 16, 2021 at 20:25

2 Answers 2

2

First off, matrices should only consist of one class type (e.g., character or integer or numeric etc.). I suggest using a data frame for columns of different class types.

d <- data.frame(num = c(1,4,7,6,5),str = c("a","b","c","a","b")) d[d$str == "a","num"] <- d[d$str == "a","num"]*2 > d num str 1 2 a 2 4 b 3 7 c 4 12 a 5 5 b 
Sign up to request clarification or add additional context in comments.

Comments

1

We can use

df1 <- type.convert(as.data.frame(M), as.is = TRUE) df1$V1 <- ifelse(df1$V2 == 'a', df1$V1 * 2, df1$V1) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.