【发布时间】:2014-04-15 13:00:18
【问题描述】:
所以,我有一个名为“DATA”的 data.frame 对象。 该对象包含一个名为“Point”(DATA$Point) 的列。由于此特定列上有一些重复项,我想构建一个函数,在 DATA 中的这些重复项中仅对一行进行采样。
我一直在尝试这样做:
sort.song<-function(DATA){
Point<-levels(DATA$Point)
DATA.NEW<-DATA[1:length(Point),]
#Ideally DATA.NEW should have an empty dataframe with nrow=length(Point) and the same columns
#as in DATA. But I THINK it will work (I don't know how to do the "ideally" way)
for(i in 1:dim(DATA)[1]){ #dim(DATA)[1] always bigger than length(Point)
SUBDATA<-DATA[which(DATA$Point%in%Point[i]),]
#I need to sample one row of the original data set only of the duplicates of the same value.
#So if there isn't a duplicate of one particular value, move on. Otherwise sample one between
#those duplicates.
l<-dim(SUBDATA)[1]
if (l==1){DATA.NEW[i,]<-SUBDATA[l,]}else{lc<-sample(1:l,1)}
DATA.NEW[i,]<-SUBDATA[lc,]
}
return(DATA.NEW)
}
test<-sort.song(DATA)
但它不起作用! :( 我收到以下错误消息:
Error in `[<-.factor`(`*tmp*`, iseq, value = integer(0)) :
replacement has length zero
这可能是一个愚蠢的问题,但我在这里没有选择(完全 R 初学者)
任何帮助将不胜感激!!!!
【问题讨论】:
-
你想随机抽取重复的样本吗,如果不是这样的话
DATA[!duplicated(DATA$Point), ] -
是的,我想随机抽样重复(包括重复所基于的值)。我的意思是,函数 duplicated() 只显示重复的值。我想在重复项和重复的值之间进行采样。好的,我可能会感到困惑,因为我是 R 的新手。
标签: r function dataframe sample duplicate-data