本文介绍了如何在数据框的特定命名列上使用`assign()`或`get()`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 有没有办法为数据框内的特定列分配一个值?例如, dat2 = data.frame(c1 = 101:149,VAR1 = 151:200)j = dat2 [,VAR1]##或j =dat2 [,2] assign(j,1:50) 上述方法不起作用。也不是这样: j =dat2 assign(get(j)[,VAR1 1:50) 解决方案让我们假设我们有一个有效 data.frame每个50行 dat2 1。不要使用 assign 和 get ,如果你可以避免。 dat2 [,VAR1]在 R 。 您还可以在帮助页面中注明 assign assign不调度分配方法,所以它不能用于设置向量,名称,属性等元素。 请注意,附加列表或数据框的分配会更改附加的副本而不是原始对象:请参阅附件和。 data.frame的一列是列表的元素 您要查找的是 [[< - #分配列中的值(列表的名称元素)`VAR1` j< - dat2 [['VAR1']] 想在 dat2 VAR1 中分配新值p $ p> dat2 [['VAR1']]< - 1:50 答案对于你的问题.... 要使用获取和分配 assign('dat2',`[[& '),'VAR1',value = 2:51)) 其他方法 data.table :: set 如果您想通过引用分配 data.frame 或 data.table (仅替换现有列)然后 set $ data.table package works(even with data.frames ) library(data.table) set(dat2,j ='VAR1',value = 5:54) eval 和 bquote dat1 dat2< - data.frame(x = 2:6) (x in sapply(c('dat1',' dat2'),as.name)){ eval(bquote(。(x)[['VAR1']]< - 2:6))} eapply 或者如果您使用单独的环境 ee< - new.env() ee $ dat1 ee $ dat2 #eapply返回一个列表,所以使用list2env分配给ee list2env(eapply(ee,`[[< -`,'y',value = 1:5),envir = ee) / pre> Is there a way to assign a value to a specific column within a data frame? e.g.,dat2 = data.frame(c1 = 101:149, VAR1 = 151:200) j = "dat2[,"VAR1"]" ## or, j = "dat2[,2]"assign(j,1:50)The approach above doesn't work. Neither does this:j = "dat2"assign(get(j)[,"VAR1"],1:50) 解决方案 lets assume that we have a valid data.frame with 50 rows in each dat2 <- data.frame(c1 = 1:50, VAR1 = 51:100)1 . Don't use assign and get if you can avoid it. "dat2[,"VAR1"]" is not valid in R.You can also note this from the help page for assign assign does not dispatch assignment methods, so it cannot be used to set elements of vectors, names, attributes, etc. Note that assignment to an attached list or data frame changes the attached copy and not the original object: see attach and with.A column of a data.frame is an element of a listWhat you are looking for is [[<-# assign the values from column (named element of the list) `VAR1`j <- dat2[['VAR1']] If you want to assign new values to VAR1 within dat2, dat2[['VAR1']] <- 1:50The answer to your question....To manipulate entirely using character strings using get and assignassign('dat2', `[[<-`(get('dat2'), 'VAR1', value = 2:51))Other approachesdata.table::setif you want to assign by reference within a data.frame or data.table (replacing an existing column only) then set from the data.table package works (even with data.frames)library(data.table)set(dat2, j = 'VAR1', value = 5:54)eval and bquotedat1 <- data.frame(x=1:5)dat2 <- data.frame(x=2:6)for(x in sapply(c('dat1','dat2'),as.name)) { eval(bquote(.(x)[['VAR1']] <- 2:6))}eapplyOr if you use a separate environment ee <- new.env()ee$dat1 <- dat1ee$dat2 <- dat2# eapply returns a list, so use list2env to assign back to eelist2env(eapply(ee, `[[<-`, 'y', value =1:5), envir = ee) 这篇关于如何在数据框的特定命名列上使用`assign()`或`get()`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-18 21:38