table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)
三张具有相同结构的表格。
我想对上面的所有表格执行相同的数据操作。
rownames(table1) <- c("x", "y", "z", "v", "p")
table1 <- table1[!rownames(table1) %in% c("z", "p"), ]
上面我重新命名了行,然后根据table1的字符串将其删除。
而不是为所有三个表重复上面的代码,我怎么能一次对所有表进行这种操作?
由于
答案 0 :(得分:0)
具有重复使用功能!
table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)
do_this <- function(table) {
rownames(table) <- c("x", "y", "z", "v", "p")
return(table[!rownames(table) %in% c("z", "p"), ])
}
table1 <- do_this(table1)
table2 <- do_this(table2)
table3 <- do_this(table3)
>
> table3
[,1] [,2]
x 55 7
y 22 33
v 64 221
>
答案 1 :(得分:0)
更容易。使用lapply
,这样您就不必三次编写该函数。
table1 <- matrix(c(51,43,22,92,28,21,68,22,9,12),ncol=2,byrow=TRUE)
table2 <- matrix(c(31,72,55,94,24,21,6,22,9,12),ncol=2,byrow=TRUE)
table3 <- matrix(c(55,7,22,33,21,111,64,221,92,10),ncol=2,byrow=TRUE)
#function
tablemodification<-function(yourtable){
rownames(yourtable) <- c("x", "y", "z", "v", "p")
yourtable <- yourtable[!rownames(yourtable) %in% c("z", "p"), ]
}
lapply(list(table1, table2, table3), tablemodification)