[英]Make a function work on the LHS of the assignment operator in R
It seems like I should know the answer to this but I don't.似乎我应该知道这个问题的答案,但我不知道。 How can I write a function that will work on the lefthand side of the assignment operator?
我如何编写一个可以在赋值运算符左侧工作的 function? Eg, in the example below how can I make a function called
my.rownames
that I can put on the LHS of <-
to assign rownames
to foo
.例如,在下面的示例中,我如何制作一个名为
my.rownames
的rownames
,我可以将其放在<-
的 LHS 上以将行名分配给foo
。
# get rownames and change them
foo <- rownames(mtcars)
foo <- paste("x",foo)
# put altered rownames back
rownames(mtcars) <- foo
# create a new function my.rownames
my.rownames <- rownames
# works
my.rownames(mtcars)
# doesn't work
my.rownames(mtcars) <- foo
According to ?rownames
根据
?rownames
row.names returns a character vector.
row.names 返回一个字符向量。
row.names<- returns a data frame with the row names changed.
row.names<- 返回行名称更改的数据框。
`my.rownames<-` <- `rownames<-`
Also,还,
There are generic functions for getting and setting row names, with default methods for arrays.
有用于获取和设置行名的通用函数,默认方法为 arrays。 The description here is for the data.frame method.
这里的描述是针对 data.frame 方法的。
.rowNamesDF<-
is a (non-generic replacement) function to set row names for data frames, with extra argument make.names..rowNamesDF<-
是(非通用替换)function 用于设置数据帧的行名称,带有额外的参数 make.names。 This function only exists as workaround as we cannot easily change the row.names<- generic without breaking legacy code in existing packages.此 function 仅作为解决方法存在,因为我们无法轻松更改 row.names<- generic 而不破坏现有包中的旧代码。
it should work它应该工作
data(mtcars)
my.rownames(mtcars) <- foo
head(mtcars)
# mpg cyl disp hp drat wt qsec vs am gear carb
#x Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
#x Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
#x Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
#x Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
#x Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
#x Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.