r - 删除数据框每一列中的相同值,并指定给定列中值的位置
问题描述
第一:我需要一些提示如何最快地做到这一点,因为我想将它多次应用于具有很多行的数据帧。我想在数据框的每一列中删除相同的值。数据帧的每一列都是给定因子的排列,无需替换。
例如,我从每列中删除值“1”:
column<-1:20
cbind(sample(column))
data <- matrix(column , length(column) , 5)
data<-apply(data,2, sample)
for (n in 1:length(data[1, ])) {
data[, n]<-c(data[-which(data[,n]==1), n], 1)
}
data <- data[-length(data[,1]),]
第二:我想指定给定列中值相对于第一列的位置。
pos <- function(data){
Position <- match(data[,1],data[,1])
Position <- as.data.frame(Position)
for (i in 2:length(data[1,])) {
Position <- cbind(Position, match(data[,1],data[,i]))
}
return(Position)
}
如果您有任何更快的建议,请随时在下面提及。
解决方案
第1部分
您可以按列进行apply
apply(data, 2, function(x) x[-which(x == 1)])
# [,1] [,2] [,3] [,4] [,5]
# [1,] 13 12 5 3 19
# [2,] 8 20 8 17 20
# [3,] 17 4 11 10 2
# [4,] 20 2 13 16 4
# [5,] 4 16 12 4 10
# [6,] 14 8 19 20 7
# [7,] 9 9 3 15 8
# [8,] 5 10 2 14 15
# [9,] 3 13 15 5 12
#[10,] 15 6 16 9 18
#[11,] 12 15 10 6 11
#[12,] 11 3 7 12 13
#[13,] 2 5 17 19 16
#[14,] 6 7 9 18 6
#[15,] 16 17 6 11 17
#[16,] 10 14 18 7 14
#[17,] 18 11 20 8 9
#[18,] 19 19 4 2 3
#[19,] 7 18 14 13 5
第2部分
cbind(1:nrow(data), apply(data[, -1], 2, function(x) match(data[, 1], x)))
# [,1] [,2] [,3] [,4] [,5]
# [1,] 1 10 4 20 13
# [2,] 2 6 2 18 8
# [3,] 3 16 13 2 16
# [4,] 4 2 17 6 2
# [5,] 5 3 18 5 4
# [6,] 6 17 20 8 17
# [7,] 7 8 14 11 18
# [8,] 8 14 1 9 20
# [9,] 9 7 19 10 6
#[10,] 10 13 7 1 19
#[11,] 11 12 9 7 9
#[12,] 12 1 5 13 10
#[13,] 13 18 3 16 12
#[14,] 14 4 8 19 3
#[15,] 15 11 15 12 15
#[16,] 16 5 10 4 14
#[17,] 17 9 11 3 5
#[18,] 18 20 16 15 11
#[19,] 19 19 6 14 1
#[20,] 20 15 12 17 7
我们确认第 1 列 ( =13
) 中的第一个条目与第 2 列中的第 10 个条目匹配,与第 3 列中的第 4 个条目匹配,依此类推。
样本数据
set.seed(2017)
column<-1:20
cbind(sample(column))
data <- matrix(column , length(column) , 5)
data<-apply(data,2, sample)
data
# [,1] [,2] [,3] [,4] [,5]
# [1,] 13 12 5 3 19
# [2,] 8 20 8 17 20
# [3,] 17 4 11 10 2
# [4,] 20 2 13 16 4
# [5,] 4 16 12 4 10
# [6,] 14 8 19 20 1
# [7,] 9 1 3 15 7
# [8,] 5 9 2 14 8
# [9,] 1 10 15 5 15
#[10,] 3 13 16 1 12
#[11,] 15 6 10 9 18
#[12,] 12 15 7 6 11
#[13,] 11 3 17 12 13
#[14,] 2 5 9 19 16
#[15,] 6 7 6 18 6
#[16,] 16 17 18 11 17
#[17,] 10 14 20 7 14
#[18,] 18 11 4 8 9
#[19,] 19 19 1 2 3
#[20,] 7 18 14 13 5
推荐阅读
- java - 用于替换逗号的复杂正则表达式模式
- php - Laravel 中的配置助手
- asp.net - 连接下拉列表中的两个字段
- python - Adam 优化器 - ValueError:tf.function-decorated 函数试图在非第一次调用时创建变量
- node.js - Node JS请求获取原始url
- simulink - 如何将结构用作 simulink 子系统的参数并将内部的字段用作模块参数?
- c++ - 创建一个模板函数,根据模板参数类型条件返回不同的元组类型
- javascript - Vue 中的 STLLoader 无法正常工作
- python - ValueError:使用 sklearn 的 train_test_split 时
- c# - 如何使用 C#“查询”Active Directory