brucezepplin
brucezepplin

Reputation: 9752

how can I add to columns in R

I cannot seem to add two columns in R.

when I try

dat$V1 + dat$V2

I get

[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Warning message:
In Ops.factor(dat$V1, dat$V2) : + not meaningful for factors

lots of other questions suggest to do as I have done, however as you can see this does not work for me. what is the problem?

Upvotes: 2

Views: 232

Answers (1)

akrun
akrun

Reputation: 886948

Try to convert your factor columns to numeric: If V1 and V2 are 1st two columns.

dat[,1:2] <- lapply(dat[,1:2], function(x) as.numeric(as.character(x)))

dat$V1 +dat$V2

For example:

dat <- data.frame(V1= factor(1:5), V2= factor(6:10))
dat$V1+dat$V2
#[1] NA NA NA NA NA
#Warning message:
#In Ops.factor(dat$V1, dat$V2) : + not meaningful for factors

dat[,1:2] <- lapply(dat[,1:2], function(x) as.numeric(as.character(x)))

dat$V1 +dat$V2
#[1]  7  9 11 13 15

Upvotes: 4

Related Questions