r - Subtract values of a single row from all relevant columns in a data frame -
i have following data set:
foo=data.frame(index=rep(1:10,3), type=rep(c("a","b","c"),each=10), ping=rnorm(30), pong=runif(30))
i want subtract values of columns ping
, pong
index==5
, type=="b"
, whole columns ping
, pong
. works:
vec=matrix(subset(foo,index==5 & type=="b",select=ping:pong),2,1) foo[,c("ping","pong")]=foo[,c("ping","pong")]-vec
however, i'm surprised had specify vec
column vector, instead row vector. have thought need subtract same row vector (similar subsets of the) rows of foo
. can explain why is? also, if same result can obtained simpler or cleaner code, please let me know.
you want this:
myselect <- with(foo, index ==5 & type == "b") mycol <- c('ping','pong') foo[, mycol] <- foo[, mycol] - as.list(foo[myselect, mycol])
vec
should list, substraction of lists done element element. want, , you're doing actually:
first of all, don't specify vec
matrix. if use matrix()
instead of as.matrix()
on list, list. , data frame list, matrix()
gives list attribute "dim". attribute makes matrix, but:
> str(vec) list of 2 $ : num 0.704 $ : num 0.164 - attr(*, "dim")= int [1:2] 2 1
what use here, side effect of function matrix()
. drops other attributes, removes data.frame
information of vec
, makes list. if vec
still data frame, wouldn't work. can use mathematical operator when both data frames have same size. , not case here.
> vec=subset(foo,index==5 & type=="b",select=ping:pong) > foo[,c("ping","pong")]-vec error in ops.data.frame(foo[, c("ping", "pong")], vec) : ‘-’ defined equally-sized data frames
you shouldn't make matrix. if do, r recycle matrix , dataframe column-wise. means substracts first value of vec first of foo$ping, second value of vec second of foo$ping, first value of vec again third value of foo$ping , forth. doesn't matter in direction put matrix, it's same (wrong!) result:
mytest<- matrix(c(-10,10), nrow = 1) mytest2 <- t(mytest) myfoo <- foo[,c('ping','pong')] all.equal(myfoo - mytest, myfoo - mytest2)
Comments
Post a Comment