我有一个矩阵:https://dl.dropbox.com/u/22681355/mat.csv
mat<-read.csv("mat.csv")
sub<-c(123,132)
我想更改垫子的第7列中的值,其中mat $ V2 = sub
我可以使用以下方法选择此子集:
set<- subset(mat, mat$V2 %in% sub)
set[,7]<-set[,7]+1
然后以某种方式将'set'与'mat'中的相同行匹配。
但有更简单的方法吗?
答案 0 :(得分:1)
mat[7] <- mat[7] + mat$V2 %in% sub
会做到这一点。
如果您希望更改V7
列中的值:
mat["V7"] <- mat["V7"] + mat$V2 %in% sub
答案 1 :(得分:0)
你应该看一些twotorials
# download and read in your file from dropbox
tf <- tempfile()
library(httr)
csvpage <- GET( "https://dl.dropbox.com/u/22681355/mat.csv" )
writeBin(content(csvpage, "raw"), tf )
# import the data into R
mat <- read.csv( tf )
# note read.csv creates a data frame not a matrix
class( mat )
# create your sub object
sub <- c(123,132)
# subset the matrix..
# show all rows where V2 is equal to any of the contents of sub
mat[ mat$V2 %in% sub , ]
# access only the V7 column for rows where V2 is equal to the contents of sub
mat[ mat$V2 %in% sub , 'V7' ]
# overwrite the V7 column with MISSING
# for rows where V2 is equal to the contents of sub
mat[ mat$V2 %in% sub , 'V7' ] <- NA
# OR
# overwrite the V7 column with the value of V2 (which matched something in sub)
# for rows where V2 is equal to the contents of sub
mat[ mat$V2 %in% sub , 'V7' ] <- mat[ mat$V2 %in% sub , 'V2' ]
# OR
# overwrite the V7 column with itself plus one
# for rows where V2 is equal to the contents of sub
mat[ mat$V2 %in% sub , 'V7' ] <- mat[ mat$V2 %in% sub , 'V7' ] + 1