我试图找到一种方法,将两个值存储在向量的一个索引中。
我有一个矩阵,我正在把它转换成矢量坐标,这样我就可以得到这个向量的随机样本,然后把这些样本的位置转换成矩阵坐标。
filter_function<-function(df,perc){
rows<-dim(df)[1]
cols<-dim(df)[2]
vec<-vector("list",rows*cols)
for(i in 1:rows){
for(j in 1:cols){
vec[(i-1)*cols+j]<-df[i,j]
}
}
n<-rows*cols
filter<-sample(vec,n*perc)
}我遇到的问题是,函数sample不返回向量坐标,也不知道如何将行和列值转换回我。我想知道是否有一种替代方法,可以将第8行更改为如下所示:
vec[(i-1)*cols+j]<-c(i,j)这显然给了我错误信息。
在vec(i-1)* cols +j <- c(i,j)中:要替换的项目数不是替换长度的倍数。
所以我想知道我能不能做点类似的事?一旦我有了坐标,我需要在理想的情况下能够快速地移除这些位置中的值,如下所示
df<-df[-filter]注意:我的数据有大量的0和1的重复,以及两者之间的所有内容,所以不需要随机抽取样本,然后使用which或match函数。
请帮帮我!
发布于 2017-08-07 22:29:31
您可以使用unlist完成这一任务。
示例数据
df <- as.data.frame(matrix(1:25,nrow=5))
V1 V2 V3 V4 V5
1 1 6 11 16 21
2 2 7 12 17 22
3 3 8 13 18 23
4 4 9 14 19 24
5 5 10 15 20 25操作
将数据帧unlist为向量。注意,它按列的顺序取消了它的列表。
m <- unlist(df)
# V11 V12 V13 V14 V15 V21 V22 V23 V24 V25 V31 V32 V33 V34 V35 V41 V42 V43 V44 V45 V51 V52 V53 V54 V55
# 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25sample随机指数
set.seed(1)
index <- sample(1:length(m), 1)
# 2获取数据帧中的值
R <- ifelse(index %% nrow(df) == 0, nrow(df), index %% nrow(df)) # row
C <- ifelse(index %% nrow(df) == 0, index / nrow(df), floor(index / nrow(df))+1) # column
df[R,C]
# 2更详细地查看上面的ifelse语句。
若要将向量中的索引转换为数据帧中的索引,请首先考虑column-index。如果index在1:5之间,值在df的第1列,如果在6:10之间,则值在df的第2列,等等。为了得到column-index,我们可以做一些类似(但不是完全)的事情,index / number of rows in df。为了处理像index==2这样的值,它给了2 / 5 = 0.4,我想舍入floor( 0.4 ) = 0,然后添加1。但是,当index==multiples of 5给出5 / 5 = 1; floor(1) + 1 = 2时,这是行不通的。因此,我使用ifelse来处理这个问题。如果index is multiple of 5 (index %% nrow(df) == 0) == T,则使用方程index / nrow(df),否则使用方程地板(index/ nrow(df))+1。对于使用模的row-index,用%%返回余数。
复核
让我们确保能够为每个可能的索引找到正确的行和列
for (index in 1:25) {
R <- ifelse(index %% nrow(df) == 0, nrow(df), index %% nrow(df))
C <- ifelse(index %% nrow(df) == 0, index / nrow(df), floor(index / nrow(df))+1)
print(df[R,C])
}
# 1
# 2
# 3
etchttps://stackoverflow.com/questions/45556264
复制相似问题