m1 <- matrix(1:12, nrow=3, ncol=4)
m1$m1.sum <- rowSums(m1[, c(1,3)])
I just tried to use function ‘rowSums’ and R said that I have to name the columns.
Warning message:
In m1$m1.sum <- rowSums(m1[, c(1, 3)]) : Coercing LHS to a list
So I’ve tried to name the columns with the function ‘names’.
names(m1) <- c(1:4)
And I had problems like codes below. Idk What happened to my try. Would you give me a hand please?
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
attr(,"names")
[1] "1" "2" "3" "4" NA NA NA NA NA NA NA NA
CodePudding user response:
The correct answer was provided by Rui Barradas, however, I suggest another solution that works with your code if m1
is a data.frame
Sample data:
m1<- data.frame(var1 = c(1, 2, 3),
var2 = c(4, 5, 6),
var3 = c(7, 8, 9),
var4=c(10,11,12))
Sample code:
m1$row_sum <- rowSums(m1[ , c(1,3)], na.rm=TRUE)
Output:
var1 var2 var3 var4 row_sum
1 1 4 7 10 8
2 2 5 8 11 10
3 3 6 9 12 12
CodePudding user response:
you could also use colnames()
as follows:
m1 = data.frame(c(1, 2, 3),
c(4, 5, 6),
c(7, 8, 9),
c(10,11,12))
colnames(m1) = c("var1", "var2", "var3", "var4")
and for renaming specific columns, for example the second, do:
colnames(m1)[2] = "var2_new"