我正在做条件,我想匹配2个不同列中的值,并且它们必须将其赋值给另一列。当我写语句
for (l in 1:k) {
for(i in 1:n) {
if(y_related[i,2]==con_f[l]) {
y_out[l]=y_related[i,1]
}
}
}
然后它不起作用!但是,如果我用它的数值替换con_f,说是0.004,那么它就可以了。但我想自动运行它,因为我不想每次都写数字值!
详细示例:
y_related=matrix(NA,1000,2)
y_related[,1]=rnorm(1000,5,10)
y_related[,2]=rank(y_related[,1])/1000
con_f=matrix(NA,250,1)
for(x in 1:250) {
con_f[x]=(1-((x-1)/250))
}
y_out=matrix(NA,250,1)
for (l in 1:250) {
for(i in 1:1000) {
if(y_related[i,2]==con_f[l]) {
y_out[l]=y_related[i,1]
}
}
}
答案 0 :(得分:0)
这听起来像功能merge
的工作# Turn them in to data frames, and rename to sensible names
y_related_df <- as.data.frame(y_related)
names(y_related_df) <- c("value", "variable")
con_f_df <- as.data.frame(con_f)
names(con_f_df) <- c("variable")
# merge allows you to join on a vector of variables, and then move the data from
# y in to x as we've done a left join (all.x=TRUE)
output <- merge(x=con_f_df, y=y_related_df, by="variable", all.x=TRUE)
output
如果您不熟悉不同类型的联接,请查看this stackoverflow post
merge
非常有用,我一直都在使用