-2

我有一个矩阵:https ://dl.dropbox.com/u/22681355/mat.csv

mat<-read.csv("mat.csv")
sub<-c(123,132)

我想为 mat$V2=sub 的那些行更改 mat 的第 7 列中的值

我可以使用以下方法选择此子集:

set<- subset(mat, mat$V2 %in% sub)
set[,7]<-set[,7]+1

然后以某种方式将“set”与“mat”中的相同行匹配。

但是有没有更简单的方法来做到这一点?

4

2 回答 2

1
   mat[7] <- mat[7] + mat$V2 %in% sub

会成功的。


如果您希望更改列中的值V7

mat["V7"] <- mat["V7"] + mat$V2 %in% sub
于 2012-12-13T11:14:18.100 回答
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
于 2012-12-13T11:22:20.673 回答