[英]Make a function work on the LHS of the assignment operator in R
似乎我應該知道這個問題的答案,但我不知道。 我如何編寫一個可以在賦值運算符左側工作的 function? 例如,在下面的示例中,我如何制作一個名為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
根據?rownames
row.names 返回一個字符向量。
row.names<- 返回行名稱更改的數據框。
`my.rownames<-` <- `rownames<-`
還,
有用於獲取和設置行名的通用函數,默認方法為 arrays。 這里的描述是針對 data.frame 方法的。
.rowNamesDF<-
是(非通用替換)function 用於設置數據幀的行名稱,帶有額外的參數 make.names。 此 function 僅作為解決方法存在,因為我們無法輕松更改 row.names<- generic 而不破壞現有包中的舊代碼。
它應該工作
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.