如何在数据框的特定命名列上使用“assign()"或“get()"? [英] How to use `assign()` or `get()` on specific named column of a dataframe?
问题描述
有没有办法为数据框中的特定列赋值?例如,
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)
推荐答案
让我们假设我们有一个 valid data.frame,每个 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.如果可以避免,请不要使用 assign
和 get
.
1 . Don't use assign
and get
if you can avoid it.
"dat2[,"VAR1"]"
在 R
中无效.
您也可以从 assign
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.
data.frame 的一列是列表的一个元素
A column of a data.frame is an element of a list
你要找的是[[<-
# assign the values from column (named element of the list) `VAR1`
j <- dat2[['VAR1']]
如果您想在 dat2
内为 VAR1
分配新值,
If you want to assign new values to VAR1
within dat2
,
dat2[['VAR1']] <- 1:50
<小时>
你的问题的答案......
使用 get
和 assign
assign('dat2', `[[<-`(get('dat2'), 'VAR1', value = 2:51))
<小时>
其他方法
data.table::set
如果您想在 data.frame
或 data.table
(仅替换现有列)中通过引用分配,则 set
来自data.table
包有效(即使使用 data.frames
)
Other approaches
data.table::set
if 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
和 bquote
dat1 <- 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))
}
<小时>
eapply
或者如果你使用单独的环境
eapply
Or if you use a separate environment
ee <- new.env()
ee$dat1 <- dat1
ee$dat2 <- dat2
# eapply returns a list, so use list2env to assign back to ee
list2env(eapply(ee, `[[<-`, 'y', value =1:5), envir = ee)
这篇关于如何在数据框的特定命名列上使用“assign()"或“get()"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!