gpt4 book ai didi

r - paste0-在 plyr :rename (now with update) 中构建一个参数

转载 作者:行者123 更新时间:2023-12-02 07:05:44 25 4
gpt4 key购买 nike

我在 this answer 工作按照 Jared 的建议,尝试优化 plyr:rename 中的第二个参数.

简而言之,他们正在使用 plyr 像这样重命名数据框中的某些列,

df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df
newNames <- c("new_col1", "new_col2", "new_col3")
oldNames <- names(df)

require(plyr)
df <- rename(df, c("col1"="new_col1", "col2"="new_col2", "col3"="new_col3"))
df

顺带一提Jared写道“[a]你可以创造性地使第二个参数重命名,这样它就不是那么手动了。”

我试过像这样有创意

df <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df
secondArgument <- paste0('"', oldNames, '"','=', '"',newNames, '"',collapse = ',')
df <- rename(df, secondArgument)
df

但是它不起作用,谁能帮我自动化这个?

谢谢!

更新 Sun Sep 9 11:55:42PM

我意识到我的问题应该更具体一些。

我正在使用 plyr::rename,因为在我的现实生活示例中,我有其他变量,但我并不总是知道要重命名的变量的位置。我会更新我的问题

我的案例看起来像这样,但有 100 多个变量

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
df2 <- rename(df2, c("col1"="new_col1", "col3"="new_col3"))
df2

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
newNames <- c("new_col1", "new_col3")
oldNames <- names(df[,c('col1', 'col3')])
secondArgument <- paste0('"', oldNames, '"','=', '"',newNames, '"',collapse = ',')
df2 <- rename(df2, secondArgument)
df2

如果有任何我需要澄清的地方,请添加评论。

最佳答案

修改问题的解决方案:

df2 <- data.frame(col1=1:3,col2=3:5,col3=6:8)
df2
newNames <- c("new_col1", "new_col3")
oldNames <- names(df2[,c('col1', 'col3')])

(根据定义,oldNames 不等于c('col1','col3') 吗?)

plyr 的解决方案:

secondArgument <- setNames(newNames,oldNames)
library(plyr)
df2 <- rename(df2, secondArgument)
df2

或者在 base R 中你可以这样做:

names(df2)[match(oldNames,names(df2))] <- newNames

关于r - paste0-在 plyr :rename (now with update) 中构建一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12342996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com