我想在空数据框中插入预先存在的数据(根据一列的名称)。让我们说我的空数据是:
#define empty data.frame
predictor.names <- c("LO3","Tx","Gh","RH","SR","ST","TC","U10","WF","SF","F","VW","VS","V","D","day")
dat <- data.frame("pred"=predictor.names,"MAM"=0)
rownames(dat) <- predictor.names
现在,我想用以下值填充行:
x Freq
SR 392
RH 350
day 253
Tx 90
LO3 28
ST 7
TC 5
WF 5
VS 2
SF 1
然后,我试过了:
dat[which(dat$pred%in%temp[[1]]),2] <- temp[[2]]
但它不起作用,因为变量的顺序是不同的.. 它为第一个LO3增加了392,依此类推...... 所以我想用循环来做这个...但必须有另一种更简单的方法.. 有什么想法/建议吗?
提前致谢!
答案 0 :(得分:3)
您可以尝试使用match
获取数字索引并使用它来分配值。
indx <- match(temp$x, dat$pred)
dat$MAM[indx] <- temp$Freq
temp <- structure(list(x = c("SR", "RH", "day", "Tx", "LO3", "ST",
"TC",
"WF", "VS", "SF"), Freq = c(392L, 350L, 253L, 90L, 28L, 7L, 5L,
5L, 2L, 1L)), .Names = c("x", "Freq"), class = "data.frame",
row.names = c(NA, -10L))